﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Windows.Forms;
using System.Diagnostics;
using System.ComponentModel;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Reflection;
using System.Configuration;
using System.Security;
using System.Threading;
using System.Net;
using System.Xml;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Data.SqlClient;
using ERPForms;
using ERPStudio;
using System.Data;
using System.Drawing;
using Microsoft.Reporting.WinForms;

namespace Fares
{
    public partial class DocumenteFrm : FrmWorkspace
    {
        [DllImport("Kernel32.dll")]
        public static extern bool Beep(UInt32 frequency, UInt32 duration);


        #region Membrii variabile
        public int LunaCurenta = 0;
        public int AnulCurent = 0;

        private String SerieNumerica = String.Empty;
        private Dictionary<String, String> SeriiNumerice = new Dictionary<string, string>();
        /// <summary>
        /// Macheta se foloseste pentru documentele de intrare
        /// </summary>
        private Boolean DocumenteIntrare = true;
        private List<Int16> RegimuriTVAZero = null;
        private List<Int16> RegimuriTVANeZero = null;
        private List<BindingSource> listBS = new List<BindingSource>();
        private List<SqlDataAdapter> listTA = new List<SqlDataAdapter>();
        private List<BindingSource> listChitBS = new List<BindingSource>();
        private List<SqlDataAdapter> listChitTA = new List<SqlDataAdapter>();
        /// <summary>
        /// listele pentru dimensiuni
        /// </summary>
        private List<ComboBox> listDimCombo = new List<ComboBox>();
        private List<Label> listDimLabel = new List<Label>();
        private List<TextBox> listTextBox = new List<TextBox>();
        private Int64 CodPartenerPentruBC = 0;

        private Boolean AfiseazaProprietarDocument = false;
        private Boolean FaraTVA = true;
        private Boolean FolosesteVarianta = true;
        private Boolean CotaTVAActivaDetaliu = true;
        private Boolean FolosesteDepartamente = true;
        private Boolean FolosesteDataLivrare = true;
        private Boolean FaraCodArticol = false;
        private Boolean RegimFiscalDetaliu = false;
        private Boolean FolosesteValoareTotalaCuAdaos = false;
        private Boolean ParteneriProprii = false;
        private Decimal CotaTVAImplicita = Decimal.Zero;
        private Boolean SalveazaCuUrmatorulNumar = true;
        private Boolean SalvareCuAdaugare = true;
        private Boolean FolosesteObservatii = true;
        private Boolean AfiseazaDoarDocumenteleCurente = false;
        private Boolean AfiseazaSemnaturiTiparire = true;
        private Boolean GestiuneaStocurilor = true;
        private Boolean Bugetara = false;
        private Boolean FolosesteTVAArticol = false;
        private Boolean Valuta = false;
        private Int16 ValutaImplicita = -1;
        private Int16 BancaImplicita = -1;
        private Int16 MonedaImplicita = -1;
        private Boolean AvizExpeditieCuTVA = false;
        private Boolean ComenziFaraPret = false;
        private Boolean ProdusePeParteneri = false;
        private Boolean ProductieActivata = false;
        /// <summary>
        /// numarul de inregistrari adaugate
        /// </summary>
        private Int32 NoRecAdd = 0;
        private Boolean _initDialog = false;
        DataSets.ESRPDataSet.DocumenteRow documentAnterior = null;
        private Int32 IndexButonGF = -1; 
        private Int16 FelDocument = -1;
        #endregion

        DataSets.ESRPDataSet.FaresSetupRow FSRow = null;


        private DocumenteFrm():base(null)
        {
            InitializeComponent();
        }

        public DocumenteFrm(ModuleClass mInfo,Boolean intrare,Int16 felDoc=-1)
            : base(mInfo)
        {
            FelDocument = felDoc;
            RegimuriTVAZero = new List<Int16>();
            RegimuriTVANeZero = new List<Int16>();
            DocumenteIntrare = intrare;
            HandleSalvare += new EventHandler(Salvare);
            InitializeComponent();
            
            docDetaliuDGV.m_AutoCompletionColumns.Add(IDArticolColumn);
            docDetaliuDGV.m_AutoCompletionColumns.Add(IDCodArticolColumn);
            docDetaliuDGV.m_AutoCompletionColumns.Add(IDVariantaArticolColumn);
            docDetaliuDGV.m_AutoCompletionColumns.Add(ArtAlColumn);



            this.HandleRezumat += new EventHandler(Rezumat_Documente);
            this.HandleAfterAdd += new AfterAddHandler(DocumenteFrm_HandleAfterAdd);
            this.HandleTiparire += new EventHandler(Tiparire);
            this.HandleDel += new EventHandler(Sterge);
            this.HandleBeforeDelGrid += new BeforeDelGridHandler(DocumenteFrm_HandleBeforeDelGrid);
            this.HandleBeforeDelAfterMessage += DocumenteFrm_HandleBeforeDelAfterMessage;
            HandlerValidatingAfterEndEdit += DocumenteFrm_HandlerValidatingAfterEndEdit;
            
            documenteTableAdapter.Adapter.RowUpdated += new SqlRowUpdatedEventHandler(DocumenteAdapter_RowUpdated);
            documenteTableAdapter.Adapter.RowUpdating += new SqlRowUpdatingEventHandler(Adapter_RowUpdating);
            documenteDetaliuTableAdapter.Adapter.RowUpdating += new SqlRowUpdatingEventHandler(Adapter_RowUpdatingDocumentDetaliu);
            documenteDetaliuTableAdapter.Adapter.RowUpdated += new SqlRowUpdatedEventHandler(DocumenteDetaliuAdapter_RowUpdated);

            lstPK.Add(NrDocTB);
            ///pentru accesul la arhive
            this.documenteDetaliuTableAdapter.SetTableName(ModuleInfo.AnArhiva);
            this.documenteTableAdapter.SetTableName(ModuleInfo.AnArhiva);
            if (ModuleInfo.AnArhiva != String.Empty)
                ReadOnly = true;


            
            ///valori implicite pentru document
            eSRPDataSet.Documente.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            eSRPDataSet.Documente.DataDocColumn.DefaultValue = DateTime.Now;
            eSRPDataSet.Documente.DataScadentaColumn.DefaultValue = DateTime.Now.AddDays(30);
            eSRPDataSet.Documente.DataDocReceptieColumn.DefaultValue = DateTime.Now;
            eSRPDataSet.Documente.DataContractColumn.DefaultValue = DateTime.Now;

            eSRPDataSet.Documente.IDTipDocumentColumn.DefaultValue = (FelDocument==-1)?0:FelDocument;
            eSRPDataSet.Documente.TotalValoareColumn.DefaultValue = 0.0;
            eSRPDataSet.Documente.TotalValoareTVAColumn.DefaultValue = 0.0;
            eSRPDataSet.Documente.TotalColumn.DefaultValue = 0.0;
            
            eSRPDataSet.Documente.UserIdColumn.DefaultValue = mInfo.UserID;
            eSRPDataSet.Documente.ValoareTotalaCuAdaosColumn.DefaultValue = Decimal.Zero;
            eSRPDataSet.Documente.DataStartProductieColumn.DefaultValue = DateTime.Now;
            eSRPDataSet.Documente.NrDocColumn.DefaultValue = String.Empty;
            eSRPDataSet.Documente.DataCreationColumn.DefaultValue = DateTime.Now;
            eSRPDataSet.Documente.TotalValoareValutaColumn.DefaultValue = 0;
            
            
          

            ///valori implicite pentru document detaliu
            eSRPDataSet.DocumenteDetaliu.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            eSRPDataSet.DocumenteDetaliu.IDUnitateMasuraColumn.DefaultValue = 0;
            eSRPDataSet.DocumenteDetaliu.ValoareTotalaCuAdaosColumn.DefaultValue = Decimal.Zero;
            eSRPDataSet.DocumenteDetaliu.ValoareUnitaraValutaColumn.DefaultValue = Decimal.Zero;
            eSRPDataSet.DocumenteDetaliu.ValoareUnitaraColumn.DefaultValue = Decimal.Zero;
            eSRPDataSet.DocumenteDetaliu.TVAIncasareColumn.DefaultValue = false;


            docDetaliuDGV.m_AutoCompletionColumns.Add(IDCodArticolColumn);
            docDetaliuDGV.m_AutoCompletionColumns.Add(IDArticolColumn);
            //docDetaliuDGV.m_AutoCompletionColumns.Add(IDVariantaArticolColumn);

            //setarea coloanei cu denumire si serviici ca se tot pierde
            /*this.IDArticolColumn.DataSource = this.articoleBindingSource;
            this.IDArticolColumn.DisplayMember = "Denumire";
            this.IDArticolColumn.ValueMember = "IDArticol";
   */
            //this.IDVariantaArticolColumn.DataSource = this.articoleVarianteBindingSource;
            //this.IDVariantaArticolColumn.DisplayMember = "Denumire";
            //this.IDVariantaArticolColumn.ValueMember = "IDVariantaArticol";
            EnableMainBrowseButton = true;
             
        }

        

        bool DocumenteFrm_HandleBeforeDelAfterMessage(object sender, EventArgs args, Boolean dingrid)
        {
            if (dingrid)
                return true;

            documenteDetaliuBindingSource.MoveFirst();
            for (int i = 0; i < documenteDetaliuBindingSource.Count; i++ )
            {
                if (LinkBindingSource.Count != 0)
                {
                    foreach (DataRowView dl in LinkBindingSource)
                        LinkBindingSource.Remove(dl);
                }
                documenteDetaliuBindingSource.MoveNext();
            }
            return true;
        }

        void Adapter_RowUpdatingDocumentDetaliu(object sender, SqlRowUpdatingEventArgs args)
        {
            if (args.StatementType == StatementType.Delete)
                return;
            //SqlDataAdapter da = sender as SqlDataAdapter;
            
        }

        void Adapter_RowUpdating(object sender, SqlRowUpdatingEventArgs args)
        {
            if (args.StatementType == StatementType.Delete)
                return;
            ///doar pentru factura fiscala de iesire
            ///
            Int32 tipDoc = Convert.ToInt32(args.Row["IDTipDocument"]);
            SqlConnection con = DeschideConexiune(workConnString);
            SqlCommand cmd = new SqlCommand("", con);

            if (args.StatementType != StatementType.Insert || tipDoc != 1)
            {
                InchideConexiune(con);
                return;
            }
            SqlDataAdapter da = sender as SqlDataAdapter;
            //Seteaza seria numerica
            
            
            cmd.CommandText = "SELECT [Serie] FROM [SeriiNumerice] WHERE IDSerie='" + SeriiNumerice["FACT"] + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object ret = cmd.ExecuteScalar();
            if (ret != null && ret != DBNull.Value)
            {
                da.InsertCommand.Parameters["@Serie"].Value = ret.ToString();
            }
            cmd.CommandText = "SELECT [UltimulNrFolosit] FROM [SeriiNumerice] WHERE IDSerie='" + SeriiNumerice["FACT"] + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            ret = cmd.ExecuteScalar();
            if (ret != null && ret != DBNull.Value)
            {
                da.InsertCommand.Parameters["@Numar"].Value = ret.ToString();
            }

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "ActSeriiNumerice";
            cmd.Parameters.Add(new SqlParameter("IDSerie", SeriiNumerice["FACT"]));
            cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
            cmd.ExecuteNonQuery();
            InchideConexiune(con);

        }

        private bool DocumenteFrm_HandleBeforeDelGrid(object sender, DataGridViewCellEventArgs e)
        {
            if (documenteDetaliuBindingSource.Count <= 1)
            {
                MessageBox.Show("Documentul trebuie sa contina cel putin o linie corecta!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                return false;
            }
            if(documenteDetaliuBindingSource.Current==null)
                return true;
            DataSets.ESRPDataSet.DocumenteDetaliuRow ddr = ((DataRowView)documenteDetaliuBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteDetaliuRow;

            LinkBindingSource.Filter = "IDDocDetaliuDest=" + ddr.IDDocumentDetaliu.ToString();
            foreach (DataRowView dtr in LinkBindingSource)
                LinkBindingSource.Remove(dtr);
            LinkBindingSource.Filter = String.Empty;
            return true;
        }

        override public void Cauta(object sender, EventArgs e)
        {
            base.Salvare(sender,e);
            EnableMainSearchButton = false;
            DocumenteSearchFrm frm = new DocumenteSearchFrm(ModuleInfo,ParteneriProprii,AfiseazaDoarDocumenteleCurente,LunaCurenta,AnulCurent,DocumenteIntrare);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (frm.Filtru == String.Empty)
                    return;
                //documenteBindingSource.Filter = frm.Filtru;
                
                documenteTableAdapter.Connection = DeschideConexiune(workConnString);
                documenteTableAdapter.FillByFiltru(eSRPDataSet.Documente, frm.Filtru,ModuleInfo.AnArhiva);
                InchideConexiune(documenteTableAdapter.Connection);
            }
            EnableMainBrowseButton = true;
            EnableMainSearchButton = true;
        }

        public static void beepTime()
        {
            //Beep(1000, 300);
            //System.Threading.Thread.Sleep(300);
            Beep(2000, 400);
            //System.Threading.Thread.Sleep(300);
            Beep(500, 200);
            //System.Threading.Thread.Sleep(300);
        }

        private void DocumenteAdapter_RowUpdated(object sender, SqlRowUpdatedEventArgs args)
        {
            if (args.Errors != null)
                throw args.Errors;
            if (args.StatementType == StatementType.Insert)
            {
                foreach (DataRow row in
                    eSRPDataSet.DocumenteDetaliu.Select("IDDocument=" + args.Row["IDDocument", DataRowVersion.Original].ToString(),
                        "IDDocument", DataViewRowState.Added))
                {
                    row["IDDocument"] = args.Row["IDDocument"];
                }

            }
        }

        private void DocumenteDetaliuAdapter_RowUpdated(object sender, SqlRowUpdatedEventArgs args)
        {
            //if (args.Errors != null)
            //    throw args.Errors;
  
            if (args.StatementType == StatementType.Insert)
            {
                DataSets.ESRPDataSet.DocumenteDetaliuRow ddr = args.Row as DataSets.ESRPDataSet.DocumenteDetaliuRow;
                if (ddr.HasVersion(DataRowVersion.Original))
                {
                    foreach (DataRow row in
                        eSRPDataSet.DocumenteDetaliuLink.Select("IDDocDetaliuDest=" + args.Row["IDDocumentDetaliu", DataRowVersion.Original].ToString(),
                            "IDDocDetaliuDest", DataViewRowState.Added))
                    {
                        row["IDDocDetaliuDest"] = args.Row["IDDocumentDetaliu"];
                    }
                }

            }
        }

        private void Rezumat_Documente(object sender, EventArgs e)
        {
            Int32 selID = -1;
            if (documenteBindingSource.Current != null)
            {
                DataSets.ESRPDataSet.DocumenteRow prr = ((DataRowView)documenteBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteRow;
                selID = (Int32)prr.IDDocument;
            }
            DocumenteRezumatFrm frm = new DocumenteRezumatFrm(ModuleInfo, DocumenteIntrare, documenteBindingSource, documenteDetaliuBindingSource,selID,AfiseazaDoarDocumenteleCurente,LunaCurenta,AnulCurent,-1,-1,-1,FelDocument,FSRow.GestiuneCantitativa);
            frm.SelectionAddOn = true;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (frm.selectedDataRow != null)
                {
                    documenteBindingSource.RemoveFilter();
                    DataSets.ESRPDataSet.DocumenteRow pr = frm.selectedDataRow.Row as DataSets.ESRPDataSet.DocumenteRow;
                    try
                    {
                        documenteBindingSource.EndEdit();
                    }
                    catch (Exception)
                    {
                        documenteBindingSource.CancelEdit();
                    }
                    documenteBindingSource.Position = documenteBindingSource.Find("IDDocument", pr.IDDocument);
                    documenteBindingSource.ResetCurrentItem();
                    SetTitle();
                }
            }
            EnableMainBrowseButton = true;
        }

        private void Gestiuni(object sender, EventArgs e)
        {
            FrmMainMdi frm = this.MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("erpforms");
            String numeClasa = "ERPForms.DepartamenteFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                    new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;
                newFrm.ShowDialog();

                departamenteTableAdapter.Connection = DeschideConexiune(workConnString);
                departamenteTableAdapter.Fill(eSRPDataSet.Departamente);
                InchideConexiune(departamenteTableAdapter.Connection);

            }
        }

        private void RezumatArticole(object sender, EventArgs e)
        {

            if (documenteDetaliuBindingSource.Current == null)
                return;
            DataSets.ESRPDataSet.DocumenteDetaliuRow rd = ((DataRowView)documenteDetaliuBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteDetaliuRow;
            DataSets.ESRPDataSet.DocumenteRow rdoc = ((DataRowView)documenteBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteRow;
            int artPos = articoleBindingSource.Position;
            Int32 idpart = -1;
            try
            {
                idpart = rd.IDArticol;
            }
            catch
            {
                idpart = -1;
            }

            ArticoleCardFrm rez = new ArticoleCardFrm(this.ModuleInfo,idpart,rdoc.IDPartener);
            rez.ShowDialog();
            Cursor.Current = Cursors.WaitCursor;
            docDetaliuDGV.SuspendLayout();
            articoleTableAdapter.Connection = DeschideConexiune(workConnString);
            articoleTableAdapter.Fill(eSRPDataSet.Articole, ModuleInfo.CodUnitate);
            articoleBindingSource.ResetBindings(false);
            if (FolosesteVarianta)
            {
                articoleVarianteTableAdapter.Connection = articoleTableAdapter.Connection;
                //face refresh pe varinate
                articoleVarianteTableAdapter.Fill(eSRPDataSet.ArticoleVariante);
                articoleVarianteBindingSource.ResetBindings(false);
            }

            this.articolePreturiTableAdapter.Connection = articoleTableAdapter.Connection;
            this.articolePreturiTableAdapter.Fill(this.eSRPDataSet.ArticolePreturi);

            InchideConexiune(articoleTableAdapter.Connection);
            if (artPos != articoleBindingSource.Position)
                articoleBindingSource.Position = articoleBindingSource.Find("IDArticol", idpart);
            docDetaliuDGV.ResumeLayout();
            Cursor.Current = Cursors.Default;
        }

        private void SeteazaTotalDocument(Int32 tipDoc)
        {
            Decimal newValTVA,fake, newVal = GetSum(ValoareTotalaColumn.Index, ValoareTVAColumn.Index, docDetaliuDGV, out newValTVA),newValCuAdaos
                = GetSum(ValoareTotalaCuAdaosColumn.Index, ValoareTVAColumn.Index, docDetaliuDGV, out fake),
            newValValuta = GetSum(ValoareUnitaraValutaColumn.Index, ValoareTVAColumn.Index, docDetaliuDGV, out fake,true);


            if (totalValoareTB.Value != newVal)
                totalValoareTB.Value = newVal;

            if (totalValoareTVATB.Value != newValTVA)
                totalValoareTVATB.Value = newValTVA;

            //bon fiscal
            if (tipDoc!=10 && tipDoc!=11 && (totalTB.Value != newVal + newValTVA))
                totalTB.Value = newVal + newValTVA;
            //factura
            if((tipDoc==10 || tipDoc==11) && (totalTB.Value != newVal))
                    totalTB.Value = newVal;
            
            if (totalCuAdaosTB.Value != newValCuAdaos)
                totalCuAdaosTB.Value = newValCuAdaos;
            if(Valuta)
                if (totalValutaNUD.Value != newValValuta)
                    totalValutaNUD.Value = newValValuta;
            
        }

        new public void Sterge(object sender, EventArgs e)
        {
            SeteazaTotalDocument(-1);
            if (documenteBindingSource.Count == 0)
            {
                ConditiiPB.Visible = false;
                toolTip1.SetToolTip(ConditiiPB, String.Empty);
            }
            

        }

        private void Tiparire(object sender, EventArgs e)
        {
            Salvare(this, null);
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));

            Boolean areIncasare = false;

            DataRowView dr = (DataRowView)documenteBindingSource.Current;
            if (dr == null || dr.IsNew)
                return;
            DataSets.ESRPDataSet.DocumenteRow  ddr = dr.Row as DataSets.ESRPDataSet.DocumenteRow;

            DataSets.ESRPDataSet eSRPDS = new DataSets.ESRPDataSet();
            Cursor.Current = Cursors.AppStarting;
            String linia1 = String.Empty, linia2 = String.Empty;



            PreviewRaportFrm frm = new PreviewRaportFrm("", null, ModuleInfo);
            //eSRPDataSet - este data setul cu care lucram

            SemnaturiFrm frm2 = new SemnaturiFrm(ModuleInfo);
            if (AfiseazaSemnaturiTiparire)
            {
                frm2.SelectSemnaturi = true;
                frm2.ShowDialog();
            }
            

            foreach (BindingSource bs in listBS)
                if (bs != null) bs.Dispose();
            listBS.Clear();
            listBS.Add(new BindingSource(eSRPDS, "BalconSetup"));

            listTA.Clear();
            listTA.Add(new SqlDataAdapter("SELECT * FROM [BalconSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
            listTA[0].SelectCommand.CommandType = CommandType.Text;
            listTA[0].Fill(eSRPDS.BalconSetup);

            listTA.Add(new SqlDataAdapter("SELECT * FROM [FaresSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
            listTA[1].SelectCommand.CommandType = CommandType.Text;
            listTA[1].Fill(eSRPDS.FaresSetup);
            listBS.Add(new BindingSource(eSRPDS, "FaresSetup"));

            listTA.Add(new SqlDataAdapter("SELECT * FROM [Documente] WHERE IDDocument =" + ddr.IDDocument.ToString(), cmd.Connection));
            listTA[2].SelectCommand.CommandType = CommandType.Text;
            listTA[2].Fill(eSRPDS.Documente);
            listBS.Add(new BindingSource(eSRPDS, "Documente"));

            listTA.Add(new SqlDataAdapter("SELECT * FROM [fares_viewArticoleComanda] WHERE IDDocument =" + ddr.IDDocument.ToString(), cmd.Connection));
            listTA[3].SelectCommand.CommandType = CommandType.Text;
            listTA[3].Fill(eSRPDS.fares_viewArticoleComanda);
            listBS.Add(new BindingSource(eSRPDS, "fares_viewArticoleComanda"));

            listTA.Add(new SqlDataAdapter("SELECT * FROM [fares_ViewParteneri] WHERE IDPartener =" + ddr.IDPartener.ToString(), cmd.Connection));
            listTA[4].SelectCommand.CommandType = CommandType.Text;
            listTA[4].Fill(eSRPDS.fares_ViewParteneri);
            listBS.Add(new BindingSource(eSRPDS, "fares_ViewParteneri"));

            listTA.Add(new SqlDataAdapter("SELECT * FROM [aspnet_Users] WHERE UserID ='" + ddr.UserId.ToString() + "'", DeschideConexiune("AdminConnectionString")));
            listTA[5].SelectCommand.CommandType = CommandType.Text;
            listTA[5].Fill(eSRPDS.aspnet_Users);
            listBS.Add(new BindingSource(eSRPDS, "aspnet_Users"));

            if (frm2.selectat == String.Empty)
                frm2.selectat = "-1";
            listTA.Add(new SqlDataAdapter("SELECT * FROM [Semnaturi] WHERE IDSemnatura in (" + frm2.selectat + ")", cmd.Connection));
            listTA[6].SelectCommand.CommandType = CommandType.Text;
            listTA[6].Fill(eSRPDS.Semnaturi);
            listBS.Add(new BindingSource(eSRPDS, "Semnaturi"));

            String DepartamentStr = String.Empty;
            if (!ddr.IsIDDepartamentNull())
            {
                cmd.CommandText = "Select Nume From Departamente where IDDepartament=" + ddr.IDDepartament.ToString();
                Object rDep = cmd.ExecuteScalar();
                if (rDep != null && rDep != DBNull.Value)
                    DepartamentStr = rDep.ToString();
            }



            String reprezentandStr = String.Empty;
            if (ddr.IDTipDocument != 1 && ddr.IDTipDocument != 14)
            {
                listTA.Add(new SqlDataAdapter("SELECT * FROM [Gestionari] " +
                ((!ddr.IsIDGestionarNull() && !ddr.IsIDPredatorNull())?"WHERE IDGestionar in (" + ddr.IDPredator.ToString() + "," + ddr.IDGestionar.ToString() + ")":""), cmd.Connection));
                listTA[7].SelectCommand.CommandType = CommandType.Text;
                listTA[7].Fill(eSRPDS.Gestionari);
                listBS.Add(new BindingSource(eSRPDS, "Gestionari"));
                if (!ddr.IsIDPredatorNull())
                    listBS[7].Filter = "IDGestionar=" + ddr.IDPredator.ToString();

                listBS.Add(new BindingSource(eSRPDS, "Gestionari"));
                if (!ddr.IsIDGestionarNull())
                    listBS[8].Filter = "IDGestionar=" + ddr.IDGestionar.ToString();

            }
            else
            {
                //Daca e 1 sau 14
                listTA.Add(new SqlDataAdapter("SELECT * FROM [fares_viewUnitati] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
                listTA[7].SelectCommand.CommandType = CommandType.Text;
                listTA[7].Fill(eSRPDS.fares_viewUnitati);
                listBS.Add(new BindingSource(eSRPDS, "fares_viewUnitati"));

                #region Tiparire Chitanta


                listTA.Add(new SqlDataAdapter("SELECT * FROM [fares_viewDetaliuPlata] WHERE IDDocument =" + ddr.IDDocument.ToString(), cmd.Connection));
                listTA[8].SelectCommand.CommandType = CommandType.Text;
                listTA[8].Fill(eSRPDS.fares_viewDetaliuPlata);
                listBS.Add(new BindingSource(eSRPDS, "fares_viewDetaliuPlata"));

                foreach(DataRowView drvv in  listBS[8])
                {
                    DataSets.ESRPDataSet.fares_viewDetaliuPlataRow rd = ((DataRowView)drvv).Row as DataSets.ESRPDataSet.fares_viewDetaliuPlataRow;
                    if (reprezentandStr != String.Empty)
                        reprezentandStr += ",";
                    reprezentandStr += "factura: " + rd.NrDoc.ToString() + " / " + rd.DataDoc.Day.ToString() + "." + rd.DataDoc.Month.ToString() + "." + rd.DataDoc.Year.ToString() ;
                }


                listTA.Add(new SqlDataAdapter("SELECT * FROM [DocumentePlata] WHERE IDDocumentPlata  IN (SELECT IDDocumentPlata FROM [fares_viewDetaliuPlata] WHERE IDDocument =" + ddr.IDDocument.ToString() + " )" , cmd.Connection));
                listTA[9].SelectCommand.CommandType = CommandType.Text;
                listTA[9].Fill(eSRPDS.DocumentePlata);
                listBS.Add(new BindingSource(eSRPDS, "DocumentePlata"));

                ///are incasare/plata pe el
                areIncasare = listBS[listBS.Count - 1].Count == 1;
                #endregion
            }

            


            String[] nume=new String[50], functii = new String[50];
            for (int i = 0; i < 50; i++)
            {
                nume[i] = String.Empty;
                functii[i] = String.Empty;
            }
            for (int i = 0; i < Math.Min(listBS[6].Count,50); i++)
            {
                listBS[6].Position = i;
                nume[i] = ((DataRowView)((BindingSource)listBS[6]).Current)["Nume"].ToString();
                functii[i] = ((DataRowView)((BindingSource)listBS[6]).Current)["Functia"].ToString();
                
            }

                      
            InchideConexiune(cmd.Connection);


            //String artAl = artAlCB.Text.Substring(0, 2);
            //String diviziune = JurnalCB.Text + "." + GetTitlu(artAl) + "." + artAlCB.Text;

            if (ddr.IDTipDocument == 9 || ddr.IDTipDocument == 12)
            {
                frm.NumeRaport = "Comenzi.rdlc";
                if (ModuleInfo.CurrentTheme == "spital")
                {
                    frm.NumeRaport = "ComenziSpital.rdlc";
                }
                frm.AddParameter("Departament", DepartamentStr, true);
            }
            if (ddr.IDTipDocument == 0 || ddr.IDTipDocument == 15)
                frm.NumeRaport = "NotaReceptie.rdlc";

            if (ddr.IDTipDocument == 13)
                frm.NumeRaport = "BonDeConsum.rdlc";

            if (ddr.IDTipDocument == 14)
                frm.NumeRaport = "AvizDeExpeditie.rdlc";

            if (ddr.IDTipDocument == 1)
            {
                frm.NumeRaport = "FacturaFiscala.rdlc";
                if (FSRow.PermiteTVALaIncasare)
                {
                    Boolean TVALaIncasarePeToataFactura = true;
                    frm.NumeRaport = "FacturaFiscalaTVAlaIncasare.rdlc";
                    ///verifica daca toate liniile au bitat TVA la incasare
                    DataSets.ESRPDataSet.DocumenteDetaliuRow[] docrt = eSRPDataSet.DocumenteDetaliu.Select("IDDocument=" + ddr.IDDocument.ToString() + " AND " + " TVAIncasare=0") as DataSets.ESRPDataSet.DocumenteDetaliuRow[];
                    if (docrt != null && docrt.Length != 0)
                        TVALaIncasarePeToataFactura = false;
                    frm.AddParameter("TVALaIncasareToataFactura", (TVALaIncasarePeToataFactura) ? "True" : "False", true);

                }
                DialogResult retD = DialogResult.No;
                if (areIncasare)
                {
                    MessageBoxFrm mbt = new MessageBoxFrm("Selectie", "Factura fiscala are atasat un document de plata.", "Doriti tiparirea lui in continuarea facturii?",MessageBoxFrm.ImaginiMB.IntrebareIcon, null);
                    mbt.AddButton("Da", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.AddButton("Nu", 70, mbt.MessageBoxFrm_Click_No);
                    retD = mbt.ShowDialog();
                }
                frm.AddParameter("TiparesteChitanta", (retD == DialogResult.Yes)?"True":"False", true);

            }


            frm.AddDataSource("ESRPDataSet_FaresSetup", listBS[1]);
            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            frm.AddDataSource("ESRPDataSet_Documente", listBS[2]);
            frm.AddDataSource("ESRPDataSet_fares_viewArticoleComanda", listBS[3]);
            frm.AddDataSource("ESRPDataSet_fares_ViewParteneri", listBS[4]);
            frm.AddDataSource("ESRPDataSet_aspnet_Users", listBS[5]);
            frm.AddDataSource("ESRPDataSet_Semnaturi", listBS[6]);
            if (ddr.IDTipDocument == 13)
            {
                if (listBS.Count >= 9)
                {
                    frm.AddDataSource("Gestionar_predator", listBS[7]);
                    frm.AddDataSource("Gestionar_primitor", listBS[8]);
                }
            }

            if (ddr.IDTipDocument == 1 || ddr.IDTipDocument == 14)
            {
                frm.AddDataSource("ESRPDataSet_Unitati", listBS[7]);
            }
            frm.SetWindowFormat(true);



            foreach (SqlDataAdapter da in listTA)
                if (da != null) da.Dispose();
            listTA.Clear();
            InchideConexiune(cmd.Connection);
            frm.MdiParent = this.MdiParent;
            frm.dataloadHandler += new LoadDataHandler(frm_dataloadHandler);
            frm.AddParameter("Nume", nume, true);
            frm.AddParameter("Functii",functii, true);
            #region Pentru avizul de expeditie daca sa afiseze sau nu coloana de TVA
            String valAETVA = AvizExpeditieCuTVA.ToString();
            if (ddr.IDTipDocument == 14)
                frm.AddParameter("TVA", valAETVA, true);
            #endregion

            if (ddr.IDTipDocument == 12 || ddr.IDTipDocument == 9)
            {
                frm.AddParameter("CodMoneda", MonedaImplicita.ToString(), true);
                frm.AddParameter("DenumireValuta", codValutaCB.Text == String.Empty ? "lei" : codValutaCB.Text, true);
            }

            #region Daca FF are chitanta
            if (ddr.IDTipDocument == 1)
            {
                NumberToWordsConverter nc = new NumberToWordsConverter();
                String Adica = "Fara valoare";
                if(areIncasare)
                    Adica = nc.NumberToWords(Convert.ToDecimal(((DataRowView)listBS[9].Current).Row["ValoareTotala"]));
                frm.AddParameter("Adica",Adica , true);
                frm.AddParameter("Reprezentand", reprezentandStr, true);
            }
            #endregion            
            
            
            frm.Show();
            cmd.Dispose();



            Cursor.Current = Cursors.Default;
        }

        void frm_dataloadHandler(object sender, Microsoft.Reporting.WinForms.SubreportProcessingEventArgs args)
        {
            if (args.ReportPath == "Chitanta")
            {

                DataRowView dr = (DataRowView)documenteBindingSource.Current;
                if (dr == null || dr.IsNew)
                    return;
                DataSets.ESRPDataSet.DocumenteRow ddr = dr.Row as DataSets.ESRPDataSet.DocumenteRow;

                DataSets.ESRPDataSetPlati eSRPDS = new DataSets.ESRPDataSetPlati();
                SqlConnection con = DeschideConexiune(workConnString);
                foreach (BindingSource bs in listChitBS)
                    if (bs != null) bs.Dispose();
                listChitBS.Clear();
                

                listChitTA.Clear();
                listChitTA.Add(new SqlDataAdapter("SELECT * FROM [BalconSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), con));
                listChitTA[0].SelectCommand.CommandType = CommandType.Text;
                listChitTA[0].Fill(eSRPDS.BalconSetup);
                listChitBS.Add(new BindingSource(eSRPDS, "BalconSetup"));

                listChitTA.Add(new SqlDataAdapter("SELECT * FROM [FaresSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), con));
                listChitTA[listChitTA.Count - 1].SelectCommand.CommandType = CommandType.Text;
                listChitTA[listChitTA.Count - 1].Fill(eSRPDS.FaresSetup);
                listChitBS.Add(new BindingSource(eSRPDS, "FaresSetup"));

                listChitTA.Add(new SqlDataAdapter("SELECT * FROM [DocumentePlata] WHERE IDDocumentPlata  IN (SELECT IDDocumentPlata FROM [fares_viewDetaliuPlata] WHERE IDDocument =" + ddr.IDDocument.ToString() + " )", con));
                listChitTA[2].SelectCommand.CommandType = CommandType.Text;
                listChitTA[2].Fill(eSRPDS.DocumentePlata);
                listChitBS.Add(new BindingSource(eSRPDS, "DocumentePlata"));

                listChitTA.Add(new SqlDataAdapter("SELECT * FROM [fares_viewDetaliuPlata] WHERE IDDocument =" + ddr.IDDocument.ToString(), con));
                listChitTA[3].SelectCommand.CommandType = CommandType.Text;
                listChitTA[3].Fill(eSRPDS.fares_viewDetaliuPlata);
                listChitBS.Add(new BindingSource(eSRPDS, "fares_viewDetaliuPlata"));

                listChitTA.Add(new SqlDataAdapter("SELECT * FROM [fares_ViewParteneri] WHERE IDPartener =" + ddr.IDPartener.ToString(), con));
                listChitTA[4].SelectCommand.CommandType = CommandType.Text;
                listChitTA[4].Fill(eSRPDS.fares_ViewParteneri);
                listChitBS.Add(new BindingSource(eSRPDS, "fares_ViewParteneri"));

                listChitTA.Add(new SqlDataAdapter("SELECT * FROM [fares_viewUnitati] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), con));
                listChitTA[5].SelectCommand.CommandType = CommandType.Text;
                listChitTA[5].Fill(eSRPDS.fares_viewUnitati);
                listChitBS.Add(new BindingSource(eSRPDS, "fares_viewUnitati"));

                InchideConexiune(con);
                foreach (SqlDataAdapter da in listChitTA)
                    if (da != null) da.Dispose();
                listChitTA.Clear();

                args.DataSources.Add(new ReportDataSource("ESRPDataSet_FaresSetup", listChitBS[1]));
                args.DataSources.Add(new ReportDataSource("ESRPDataSet_BalconSetup", listChitBS[0]));
                args.DataSources.Add(new ReportDataSource("ESRPDataSet_DocumentePlata", listChitBS[2]));
                args.DataSources.Add(new ReportDataSource("ESRPDataSet_fares_viewDetaliuPlata", listChitBS[3]));
                args.DataSources.Add(new ReportDataSource("ESRPDataSet_fares_ViewParteneri", listChitBS[4]));
                args.DataSources.Add(new ReportDataSource("ESRPDataSet_Unitati", listChitBS[5]));

            }

        }
        /// <summary>
        /// din seria numerica curenta seteaza urmatorul numar folosit
        /// </summary>
        /// <param name="conn"></param>
        /// <returns></returns>
        private String SetNextSerialNumber(SqlConnection conn)
        {
            String valnew = "1";
            if (SeriiNumerice.Count == 0 || documenteBindingSource.Current == null)
                return valnew;

            String serieFolosita = serieFolosita = SeriiNumerice["DOC"];
            DataRowView drv = (DataRowView)documenteBindingSource.Current;
            DataSets.ESRPDataSet.DocumenteRow dr = drv.Row as DataSets.ESRPDataSet.DocumenteRow;

            if (dr.IDTipDocument == 1)
                serieFolosita = SeriiNumerice["FACT"];
            if (dr.IDTipDocument == 14)
                serieFolosita = SeriiNumerice["AE"];
            if (dr.IDTipDocument == 13)
                serieFolosita = SeriiNumerice["BC"];


            SqlCommand cmd = new SqlCommand("", conn);
            cmd.CommandText = "SELECT [UltimulNrFolosit] FROM [SeriiNumerice] WHERE IDSerie='" + serieFolosita + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object ret = cmd.ExecuteScalar();
            if (ret != null && ret != DBNull.Value)
            {
                valnew = ret.ToString();
            }

            this.NrDocTB.Text = valnew;
            
            if (drv.IsNew)
                if(dr.NrDoc != valnew)
                    dr.NrDoc = valnew;
            

            return valnew;
        }

        private void DocumenteFrm_HandleAfterAdd(object sender, DataGridViewCellEventArgs args)
        {
            if (SeriiNumerice.Count==0)
                return;


            #region Daca este document de intrare atunci nu se genereaza numar de serie
            if (DocumenteIntrare)
            {
                this.NrDocTB.Text = String.Empty;
                ActiveControl = this.NrDocTB;
            }
            else
            {
                SqlConnection conn = DeschideConexiune(workConnString);
                SqlCommand cmd = new SqlCommand("", conn);
                SetNextSerialNumber(conn);
                ///incrementarea seriei se face la salvare
                ///
                if (NoRecAdd > 0)
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "ActSeriiNumerice";
                    cmd.Parameters.Add(new SqlParameter("IDSerie", SerieNumerica));
                    cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                    cmd.ExecuteNonQuery();
                    NoRecAdd--;
                }
                else
                    NoRecAdd++;
                InchideConexiune(conn);
            }
            #endregion

            //docDetaliuDGV[IDArticolColumn.Index, args.RowIndex].Value = String.Empty;
            
            ActiveControl = NrDocTB;
            ConditiiPB.Visible = false; 
            toolTip1.SetToolTip(ConditiiPB, String.Empty);
            NrDocTB.SelectAll();

            eSRPDataSet.Documente.DataCreationColumn.DefaultValue = DateTime.Now;

        }

        private void FurnizoriHandler(object sender, EventArgs args)
        {
            if (documenteBindingSource.Current == null)
                return;
            DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                as DataSets.ESRPDataSet.DocumenteRow;

            FrmMainMdi frm = this.MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("erpforms");
            String numeClasa = "ERPForms.PartenerFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                    new object[] { ModuleInfo,true }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;
                Int64 idpart = -1;
                try
                {
                    idpart = rd.IDPartener;
                }
                catch
                {
                    idpart = -1;
                }

                mModule.InvokeMember("IDPartenerSelectat", BindingFlags.SetProperty, null, newFrm, new object[] { idpart });

                newFrm.ShowDialog();
                if (newFrm.NoRecUpdated != 0)
                {
                    int savepos = faresParteneriCUIBindingSource.Position;
                    this.fares_ParteneriCUITableAdapter.Connection = DeschideConexiune(workConnString);
                    if (ParteneriProprii)
                        this.fares_ParteneriCUITableAdapter.FillByUnitate(eSRPDataSet.fares_ParteneriCUI, ModuleInfo.CodUnitate);
                    else
                        this.fares_ParteneriCUITableAdapter.Fill(eSRPDataSet.fares_ParteneriCUI);
                    InchideConexiune(this.fares_ParteneriCUITableAdapter.Connection);
                    faresParteneriCUIBindingSource.Position = savepos;
                }
            }

        }


        bool DocumenteFrm_HandlerValidatingAfterEndEdit(object sender)
        {
            #region Validari Documente

            DataSets.ESRPDataSet.DocumenteDataTable dt = eSRPDataSet.Documente.GetChanges() as DataSets.ESRPDataSet.DocumenteDataTable;
            if (dt == null)
                return true;
            foreach (DataSets.ESRPDataSet.DocumenteRow dr in dt.Rows)
            {
                if (dr.RowState == DataRowState.Deleted)
                    continue;
                if (dr.NrDoc.Trim() == String.Empty)
                {
                    int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                    if (poz != -1)
                        documenteBindingSource.Position = poz;

                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Vă rugăm completaţi numărul documentului!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, dr);
                    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                    errorProvider1.SetError(NrDocTB, "Vă rugăm completaţi numărul documentului!");

                    return false;
                }
                /// validare data document
                if (dr.DataDoc < new DateTime(AnulCurent, LunaCurenta, 1))
                {
                    int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                    if (poz != -1)
                        documenteBindingSource.Position = poz;

                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Data documentului trebuie sa fie in perioada curenta!", String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, dr);
                    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                    errorProvider1.SetError(dataDocDTP, "Data increcta!");

                    return false;
                }
                ///Bonurile de consum nu au parteneri
                ///
                if ((dr.IDTipDocument != 13) && (dr.IDPartener == -1))
                {
                    int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                    if (poz != -1)
                        documenteBindingSource.Position = poz;

                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Vă rugăm selectaţi partenerul!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, dr);
                    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                    errorProvider1.SetError(PartenerCB, "Vă rugăm selectaţi partenerul!");
                    return false;
                }

                if (Bugetara && dr.IsIDJurnalNull())
                {
                    int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                    if (poz != -1)
                        documenteBindingSource.Position = poz;

                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Vă rugăm selectaţi sursa de finanţare!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, dr);
                    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();

                    errorProvider1.SetError(iDJurnalCB, "Vă rugăm selectaţi sursa de finanţare!");
                    return false;
                }

                DataRow[] docDet = eSRPDataSet.DocumenteDetaliu.Select("IDDocument=" + dr.IDDocument.ToString());
                if (docDet.Length== 0)
                {
                    int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                    if (poz != -1)
                        documenteBindingSource.Position = poz;
                    
                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Documentul trebuie să conţină cel puţin o linie corectă!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, dr);
                    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                    //errorProvider1.SetError(docDetaliuDGV, "Documentul trebuie să conţină cel puţin o linie corectă!");

                    return false;
                }
            }




            #endregion

            #region Validare Documente Detaliu

            DataSets.ESRPDataSet.DocumenteDetaliuDataTable ddt = eSRPDataSet.DocumenteDetaliu.GetChanges() as DataSets.ESRPDataSet.DocumenteDetaliuDataTable;
            if (ddt == null)
                return true;
            foreach (DataSets.ESRPDataSet.DocumenteDetaliuRow dr in ddt.Rows)
            {
                if (dr.RowState == DataRowState.Deleted)
                    continue;
                DataSets.ESRPDataSet.DocumenteRow[] docrt = eSRPDataSet.Documente.Select("IDDocument=" + dr.IDDocument.ToString()) as DataSets.ESRPDataSet.DocumenteRow[];
                if (docrt == null || docrt.Length == 0)
                    return false;
                DataSets.ESRPDataSet.DocumenteRow docr = docrt[0];
                DataSets.ESRPDataSet.DocumenteDetaliuLinkRow[] ddlr = eSRPDataSet.DocumenteDetaliuLink.Select("IDDocDetaliuDest=" + dr.IDDocumentDetaliu.ToString()) as DataSets.ESRPDataSet.DocumenteDetaliuLinkRow[];
                
                if ((docr.IDTipDocument == 1 || docr.IDTipDocument == 13 || docr.IDTipDocument == 14) && GestiuneaStocurilor)
                {
                    

                    DataSets.ESRPDataSet.ArticoleRow[] artrt = eSRPDataSet.Articole.Select("IDArticol=" + dr.IDArticol.ToString()) as DataSets.ESRPDataSet.ArticoleRow[];
                    if (artrt.Length == 0)
                        return false;
                    DataSets.ESRPDataSet.ArticoleRow artr = artrt[0];
                    if (artr.EsteServiciu || FSRow.GestiuneCantitativa)
                        continue;

                    if (ddlr.Length == 0)
                    {
                        int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                        if (poz != -1 && documenteBindingSource.Position != poz)
                            documenteBindingSource.Position = poz;

                        MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "La documentele de ieşire (pentru gestiunea stocurilor) este obligatorie specificarea stocurilor din care se face ieşirea!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, dr);
                        mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.ShowDialog();
                        //errorProvider1.SetError(docDetaliuDGV, "Documentul trebuie să conţină cel puţin o linie corectă!");
                        return false;
                    }
                    Decimal cantiesite = Decimal.Zero;
                    foreach (DataSets.ESRPDataSet.DocumenteDetaliuLinkRow i in ddlr)
                    {
                        cantiesite += i.Cantitate;
                    }
                    if(cantiesite != dr.Cantitate)
                    {
                        int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                        if (poz != -1 && documenteBindingSource.Position != poz)
                            documenteBindingSource.Position = poz;

                        MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Cantitatea ieşită pe document diferă de cantitatea ieşită din stoc!", "Continuaţi",MessageBoxFrm.ImaginiMB.StopIcon, dr);
                        //mbt.AddButton("Da", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.AddButton("Nu", 70, mbt.MessageBoxFrm_Click_No);
                        //if(mbt.ShowDialog()== System.Windows.Forms.DialogResult.No)
                        mbt.ShowDialog();
                        return false;
                        
                    }

                }
            } 
            #endregion

            return true;
        }

        override public void Salvare(object sender, EventArgs args)
        {

            this.SuspendLayout();
            docDetaliuDGV.Enabled = false;
            
            base.Salvare(this, args);
            docDetaliuDGV.Enabled = true;
            ResumeLayout();


            if (EroareSalvare)
                return;
            SqlConnection con = DeschideConexiune(workConnString);
            if (documenteBindingSource.Current != null)
            {
                DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                    as DataSets.ESRPDataSet.DocumenteRow;
                SalveazaDimensiuni(con, rd.IDDocument, "Documente");
            }

            if (SerieNumerica == String.Empty)
                return;

            if (NoRecAdd > 0)
            {
                SqlCommand cmd = new SqlCommand("", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "ActSeriiNumerice";
                cmd.Parameters.Add(new SqlParameter("IDSerie", SerieNumerica));
                cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                cmd.ExecuteNonQuery();
                if (iDRegimFiscalCB.SelectedValue!=null)
                    SetSetariLocale(con, "RFIM", iDRegimFiscalCB.SelectedValue.ToString(), ModuleInfo.CodUnitate);
                
                NoRecAdd = 0;
            }
            ///calculeaza totalul pentru cazul in care se sterge o linie
            ///
            if (documenteBindingSource.Current != null)
            {
                DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                    as DataSets.ESRPDataSet.DocumenteRow;
                SeteazaTotalDocument(rd.IDTipDocument);
            }
            if (SalvareCuAdaugare && args!=null)
            {
                this.SuspendLayout();
                Adauga(this, null);
                beepTime();
                ActiveControl = NrDocTB;
                this.Focus();
                NrDocTB.Focus();
                this.ResumeLayout();
            }
            documenteDetaliuTableAdapter.Connection = con;
            this.documenteDetaliuTableAdapter.Fill(this.eSRPDataSet.DocumenteDetaliu);

            InchideConexiune(con);
            if (documenteBindingSource.Count == 0)
                documenteBindingSource.Filter = String.Empty;
            
        }

        private void DocumenteFrm_Load(object sender, EventArgs e)
        {
           _initDialog = true;
            AddBindingSource(documenteBindingSource);
            AddBindingSource(documenteDetaliuBindingSource);
            AddBindingSource(LinkBindingSource);
            
            /// adauga tabelele la lista de adaptoare pentru salvarea in baza de date!
            /// 
            listTableAdaptor.Add(documenteTableAdapter.Adapter);
            listTableAdaptor.Add(documenteDetaliuTableAdapter.Adapter);
            listTableAdaptor.Add(documenteDetaliuLinkTableAdapter.Adapter);
            
            if (!this.ReadOnly)
            {
                AddButton("Copiaza", global::ERPStudio.Properties.Resources.delicious_48, Copiaza, ToolStripItemAlignment.Right, false);
                AddButton("Articole", global::ERPStudio.Properties.Resources._001_07, RezumatArticole, ToolStripItemAlignment.Right, false);
                AddButton("Partener", global::ERPStudio.Properties.Resources._001_16, FurnizoriHandler, ToolStripItemAlignment.Right, false);
                AddButton("Inc./Plata", global::ERPStudio.Properties.Resources.account_balances, IncasarePlata, ToolStripItemAlignment.Right, false);
                IndexButonGF = AddButton(">>Comanda", global::ERPStudio.Properties.Resources.book_next, GenereazaFactura, ToolStripItemAlignment.Right, false);
            }
            else
                EnableLocalSaveButton = false;
            SetCurentUnit(ModuleInfo.CodUnitate);
            if (!this.ReadOnly)
            {
                if (FolosesteDepartamente)
                    AddButton("Gestiuni", global::ERPStudio.Properties.Resources.department, Gestiuni, ToolStripItemAlignment.Right, false);

            }
            NrDocTB.Focus();
            ActiveControl = NrDocTB;
            /*if (totalValoareTVATB.Controls.Count != 0)
            {
                totalValoareTVATB.Controls[0].Visible = false;
                totalValoareTVATB.Refresh();
            }*/
            Application.DoEvents();
            _initDialog = false;

            if (PartenerCB.SelectedItem != null)
            {
                DataSets.ESRPDataSet.fares_ParteneriCUIRow pr = ((DataRowView)PartenerCB.SelectedItem).Row as DataSets.ESRPDataSet.fares_ParteneriCUIRow;
                String mesaj = String.Empty;
                if (!pr.IsContClientNull())
                    mesaj = "Cont client:" + pr.ContClient;
                mesaj += "\nCont furnizor: " + pr.Cont;
                toolTip1.SetToolTip(PartenerCB, mesaj);
            }
            
        }

        private void LoadRegimuri()
        { 
            RegimuriTVANeZero.Clear();
            RegimuriTVAZero.Clear();
            for(int i=0;i<regimFiscalBindingSource.Count;i++)
            {
                 DataSets.ESRPDataSet.RegimFiscalRow dr = ((DataRowView)regimFiscalBindingSource.List[i]).Row as DataSets.ESRPDataSet.RegimFiscalRow;
                if(dr.CuTVA)
                    RegimuriTVANeZero.Add(dr.IDRegimFiscal);
                else
                    RegimuriTVAZero.Add(dr.IDRegimFiscal);
            }
        
        }

        override public void SetCurentUnit(short vCodUnitate)
        {
            this.ModuleInfo.CodUnitate = vCodUnitate;
            SqlConnection conn = DeschideConexiune(workConnString);

            SqlCommand com = new SqlCommand(
                "INSERT INTO [DocumenteDetaliu] " +
                " ([IDDocument],[IDArticol],[Cantitate],[ValoareUnitara],[ValoareTVA],[ValoareTotala],[CodUnitate],[IDUnitateMasura] "+
                " ,[IDRegimFiscal],[CotaTVA],[TermenLivrare],[IDVariantaArticol],[Observatii],[ValoareTotalaCuAdaos]) "+
                " SELECT IDDocument,(SELECT IDArticol FROM Articole cr WHERE CodArticol='IRF0' AND cr.CodUnitate=d.CodUnitate),1,Total,TotalValoareTVA,TotalValoare,CodUnitate, "+
                " (SELECT TOP 1 IDUnitateMasura FROM UnitatiMasura),IDRegimFiscal,CotaTVA,GETDATE(),null,'',0 FROM Documente d "+
                " WHERE Not EXISTS (SELECT * FROm DocumenteDetaliu a where a.IDDocument= d.IDDocument) AND Total=0",conn);
            try 
            {
                com.ExecuteNonQuery();
            }
            catch
            {
            
            
            }
            this.faresSetupTableAdapter.Connection = conn;
            this.faresSetupTableAdapter.Fill(this.eSRPDataSet.FaresSetup, ModuleInfo.CodUnitate);
 
            Setup(conn);
            

            CreazaDimensiuni(conn);
            this.aspnet_UsersTableAdapter.Connection = DeschideConexiune("AdminConnectionString");
            this.regimFiscalTableAdapter.Connection = conn;
            this.regimFiscalTableAdapter.Fill(this.eSRPDataSet.RegimFiscal,DocumenteIntrare?"I":"O");
            LoadRegimuri();

            if (GestiuneaStocurilor)
            {
                this.documenteDetaliuLinkTableAdapter.Connection = conn;
                this.documenteDetaliuLinkTableAdapter.Fill(this.eSRPDataSet.DocumenteDetaliuLink);
            }
 
            this.articolePreturiTableAdapter.Connection = conn;
            this.articolePreturiTableAdapter.Fill(this.eSRPDataSet.ArticolePreturi);

            this.mijloaceTransportTableAdapter.Connection = conn;
            this.mijloaceTransportTableAdapter.Fill(this.eSRPDataSetContact.MijloaceTransport);
            this.contactTableAdapter.Connection = conn;
            this.contactTableAdapter.Fill(this.eSRPDataSetContact.Contact);


            this.tipProgrameSanatateTableAdapter.Connection = conn;
            this.tipProgrameSanatateTableAdapter.Fill(this.eSRPDataSet.TipProgrameSanatate);
 
            this.valutaTableAdapter.Connection = conn;
            this.valutaTableAdapter.FillByUtilizat(this.eSRPDataSet.Valuta);
           

            articoleVarianteTableAdapter.Connection = conn;
            articoleVarianteTableAdapter.Fill(eSRPDataSet.ArticoleVariante);
 
            this.aspnet_UsersTableAdapter.Fill(this.eSRPDataSet.aspnet_Users);
            InchideConexiune(this.aspnet_UsersTableAdapter.Connection);

            this.gestionariTableAdapter.Connection = conn;
            this.gestionariTableAdapter.Fill(this.eSRPDataSet.Gestionari);
            this.departamenteTableAdapter. Connection = conn;
            this.departamenteTableAdapter.Fill(this.eSRPDataSet.Departamente);
            departamenteBindingSource.Sort = "Nume";
            this.unitatiMasuraTableAdapter.Connection = conn;
            this.unitatiMasuraTableAdapter.Fill(this.eSRPDataSet.UnitatiMasura);
            if (Bugetara)
            {
                this.jurnaleTableAdapter.Connection = conn;
                this.jurnaleTableAdapter.FillByUnitate(this.eSRPDataSet.Jurnale, ModuleInfo.CodUnitate);
                if (jurnaleBindingSource.Count == 0)
                {
                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare", "Vă rugăm să adăugaţi cel puţin un capitol înainte de a adăuga un document!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, null);
                    mbt.AddButton("Iesire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                }
                this.articoleAliniateTableAdapter.Connection = conn;
                this.articoleAliniateTableAdapter.FillByUnitate(this.eSRPDataSet.ArticoleAliniate, ModuleInfo.CodUnitate);
            }


            this.admin_DocumenteDisponibileTableAdapter.Connection = conn;
            this.admin_DocumenteDisponibileTableAdapter.FillByTipOperatie
                (this.eSRPDataSet.admin_DocumenteDisponibile, this.ModuleInfo.ApplicationID,DocumenteIntrare?"I":"O");

            #region Setare tip document implicit = ultimul fel de document adaugat
            if (FelDocument == -1)
            {
                if (admin_DocumenteDisponibileBindingSource.Current != null)
                {
                    DataSets.ESRPDataSet.admin_DocumenteDisponibileRow ddr = ((DataRowView)admin_DocumenteDisponibileBindingSource.Current).Row
                        as DataSets.ESRPDataSet.admin_DocumenteDisponibileRow;
                    eSRPDataSet.Documente.IDTipDocumentColumn.DefaultValue = ddr.IDTipDocument;
                    String afis = GetSetariLocale(conn, DocumenteIntrare ? "DDIC" : "DDOC", ddr.IDTipDocument.ToString(), ModuleInfo.CodUnitate);
                    if (Convert.ToInt16(afis) != ddr.IDTipDocument)
                    {
                        eSRPDataSet.Documente.IDTipDocumentColumn.DefaultValue = Convert.ToInt16(afis);
                    }
                }
            } 
            #endregion

            


            this.articoleTableAdapter.Connection = conn;
            this.articoleTableAdapter.Fill(this.eSRPDataSet.Articole,ModuleInfo.CodUnitate);
            if(articoleBindingSource.Count!=0)
            {
                DataSets.ESRPDataSet.ArticoleRow rd = ((DataRowView)articoleBindingSource.Current).Row as DataSets.ESRPDataSet.ArticoleRow;
                eSRPDataSet.DocumenteDetaliu.IDArticolColumn.DefaultValue = rd.IDArticol;
            }
            this.documenteDetaliuTableAdapter.Connection = conn;
            this.fares_ParteneriCUITableAdapter.Connection = conn;
            this.documenteTableAdapter.Connection = conn;

            try
            {
                this.documenteDetaliuTableAdapter.Fill(this.eSRPDataSet.DocumenteDetaliu);
                if (ParteneriProprii)
                    this.fares_ParteneriCUITableAdapter.FillByUnitate(eSRPDataSet.fares_ParteneriCUI, ModuleInfo.CodUnitate);
                else
                    this.fares_ParteneriCUITableAdapter.Fill(eSRPDataSet.fares_ParteneriCUI);

                if (AfiseazaDoarDocumenteleCurente)
                {
                    if(FelDocument==-1)
                        this.documenteTableAdapter.FillByLunaCurenta(this.eSRPDataSet.Documente, ModuleInfo.CodUnitate, (decimal)LunaCurenta, (decimal)AnulCurent, DocumenteIntrare ? "I" : "O");
                    else
                        this.documenteTableAdapter.FillByLunaCurentaFel(this.eSRPDataSet.Documente, ModuleInfo.CodUnitate, (decimal)LunaCurenta, (decimal)AnulCurent, FelDocument, DocumenteIntrare ? "I" : "O");
                }
                else
                {
                    if (FelDocument == -1)
                        this.documenteTableAdapter.Fill(this.eSRPDataSet.Documente, ModuleInfo.CodUnitate, DocumenteIntrare ? "I" : "O");
                    else
                        this.documenteTableAdapter.FillFel(this.eSRPDataSet.Documente, ModuleInfo.CodUnitate,FelDocument,DocumenteIntrare ? "I" : "O");
                }
            }
            catch (Exception ex)
            {
                    TrateazaExceptie(ex);
            }

            InchideConexiune(conn);
            

            SetTitle();
            if (documenteBindingSource.Count == 0 && !this.ReadOnly)
                Adauga(this, null);
            if (!ReadOnly)
                EnableMainAddButton = true;
            
        }

        public DateTime UltimaZiLunaCurenta = DateTime.MinValue;
        private void Setup(SqlConnection wConn)
        {

            #region Setare data in format romanesc
            ///data in format romanesc
            ///
            dataScadentaDTP.Format = DateTimePickerFormat.Custom;
            dataScadentaDTP.CustomFormat = "dd.MM.yyyy";
            dataContractDTP.Format = DateTimePickerFormat.Custom;
            dataContractDTP.CustomFormat = "dd.MM.yyyy";
            dataDocDTP.Format = DateTimePickerFormat.Custom;
            dataDocDTP.CustomFormat = "dd.MM.yyyy";
            dataDocReceptieDTP.Format = DateTimePickerFormat.Custom;
            dataDocReceptieDTP.CustomFormat = "dd.MM.yyyy";
            dataStartProductieDTP.Format = DateTimePickerFormat.Custom;
            dataStartProductieDTP.CustomFormat = "dd.MM.yyyy";
            #endregion


            #region Determinarea seriilor numerice implicite

            while (faresSetupBindingSource.Current == null)
            {
                MessageBox.Show("Modulul Parteneri nu a fost configurat. \nVa rugam sa-l configurati!",
                        "Eroare",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Hand);
                FaresSetupFrm frm = new FaresSetupFrm(this.ModuleInfo);
                frm.ShowDialog();
                faresSetupTableAdapter.Connection = wConn;
                faresSetupTableAdapter.Fill(eSRPDataSet.FaresSetup, ModuleInfo.CodUnitate);
            }

            FSRow = ((DataRowView)faresSetupBindingSource.Current).Row as DataSets.ESRPDataSet.FaresSetupRow;
            if (FSRow == null)
            {
                MessageBox.Show("Eroare citire configuratie modul. \nVa rugam sa-l configurati!",
                        "Eroare",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Hand);
                return;            
            }
            SeriiNumerice.Clear();
            SeriiNumerice.Add("DOC", FSRow.IDSerie);
            SerieNumerica = FSRow.IDSerie;
            ///determina seria numerica pentru bonurile de consum
            ///

            SeriiNumerice.Add("BC", FSRow.IDSerieBC);
            SeriiNumerice.Add("BF", FSRow.IDSerieBF);
            if (!FSRow.IsIDSerieAENull())
                SeriiNumerice.Add("AE", FSRow.IDSerieAE);
            else
                SeriiNumerice.Add("AE", String.Empty);
            if (!FSRow.IsIDSerieFACTNull())
                SeriiNumerice.Add("FACT", FSRow.IDSerieFACT); 
            else
                SeriiNumerice.Add("FACT", string.Empty); 

            #endregion

            #region Determinare luna,an curent
            LunaCurenta = FSRow.LunaCurenta;
            AnulCurent = FSRow.AnCurent; 
            #endregion

            #region Setare valori implicite data
            UltimaZiLunaCurenta = new DateTime(AnulCurent, LunaCurenta, 1).AddMonths(1).AddDays(-1);
            eSRPDataSet.Documente.DataDocColumn.DefaultValue = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            if(DocumenteIntrare)
                eSRPDataSet.Documente.DataDocColumn.DefaultValue = UltimaZiLunaCurenta;
            
                


            eSRPDataSet.Documente.DataScadentaColumn.DefaultValue = UltimaZiLunaCurenta.AddDays(30);
            eSRPDataSet.Documente.DataDocReceptieColumn.DefaultValue = UltimaZiLunaCurenta;
            eSRPDataSet.Documente.DataContractColumn.DefaultValue = UltimaZiLunaCurenta;
            #endregion



            FaraTVA = FSRow.ComenziFaraTVA;

            FaraCodArticol = FSRow.FaraCodArticol;
            IDCodArticolColumn.Visible = !FaraCodArticol;

            FolosesteVarianta = FSRow.FolosesteVarinata;
            IDVariantaArticolColumn.Visible = FolosesteVarianta;

            FolosesteDepartamente = FSRow.UtilizeazaDepartament;

            departamentCB.Visible = FolosesteDepartamente;
            DepartamentL.Visible = FolosesteDepartamente;
            GestionarCB.Visible = FolosesteDepartamente;
            GestionarL.Visible = FolosesteDepartamente;

            FolosesteDataLivrare = FSRow.FolosesteTermenLivrare;
           

            CotaTVAActivaDetaliu = FSRow.CotaTVADetaliuDocument;
            CotaTVAColumn.Visible = CotaTVAActivaDetaliu;

            RegimFiscalDetaliu = FSRow.RegimFiscalDetaliu;
            regimFiscalColumn.Visible = RegimFiscalDetaliu;

            SalveazaCuUrmatorulNumar = FSRow.SalveazaCuUrmatorulNumar;

            SalvareCuAdaugare = FSRow.SalvareCuAdaugare;
            
            ///////////////// foloseste pentru gestiunea de amanunt
            FolosesteValoareTotalaCuAdaos = FSRow.FolosesteValoareCuAdaos;

            AfiseazaDoarDocumenteleCurente = FSRow.AfiseazaDoarDocumenteleCurente;

            AfiseazaSemnaturiTiparire = FSRow.AfiseazaSemnaturiTiparire;

            ComenziFaraPret = FSRow.ComandaFaraPreturi;

            Bugetara = FSRow.Bugetara;
            ArtAlColumn.Visible = Bugetara;
            iDJurnalCB.Visible = Bugetara;
            iDJurnalL.Visible = Bugetara;
            ProgramSanatateCB.Visible = Bugetara;
            ProgramSanatateL.Visible = Bugetara;
            if (!Bugetara)
            {
                observatiiTB.Height += 27;
            }

            if(!FSRow.IsFolosesteTVAArticolNull())
                FolosesteTVAArticol = FSRow.FolosesteTVAArticol;

            nrContractLabel.Visible = FSRow.FolosesteContract;
            nrContractTB.Visible = FSRow.FolosesteContract;
            dataContractDTP.Visible = FSRow.FolosesteContract;


            ProdusePeParteneri = FSRow.ProdusePePartener;
            if (Bugetara)
            {
                while (FSRow.IsJurnalImplicitNull())
                {
                    MessageBox.Show("Modulul Parteneri nu a fost configurat. \nVa rugam sa configurati jurnalul implicit!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    FaresSetupFrm frm = new FaresSetupFrm(this.ModuleInfo);
                    frm.ShowDialog();
                    faresSetupTableAdapter.Connection = wConn;
                    faresSetupTableAdapter.Fill(eSRPDataSet.FaresSetup, ModuleInfo.CodUnitate);
                    FSRow = ((DataRowView)faresSetupBindingSource.Current).Row as DataSets.ESRPDataSet.FaresSetupRow;
                }

                eSRPDataSet.Documente.IDJurnalColumn.DefaultValue = FSRow.JurnalImplicit;

                while (FSRow.IsArtAlImplicitNull())
                {
                    MessageBox.Show("Modulul Parteneri nu a fost configurat. \nVa rugam sa configurati ARTICOLUL SI ALINEATUL implicit!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    FaresSetupFrm frm = new FaresSetupFrm(this.ModuleInfo);
                    frm.ShowDialog();
                    faresSetupTableAdapter.Connection = wConn;
                    faresSetupTableAdapter.Fill(eSRPDataSet.FaresSetup, ModuleInfo.CodUnitate);
                    FSRow = ((DataRowView)faresSetupBindingSource.Current).Row as DataSets.ESRPDataSet.FaresSetupRow;
                }
                eSRPDataSet.DocumenteDetaliu.ArtAlColumn.DefaultValue = FSRow.ArtAlImplicit;
            }
            
            ///////////////// foloseste pentru gestiunea de amanunt

            #region Optiunea Observatii
            FolosesteObservatii = FSRow.FolosesteObservatii;

            observatiiTB.Visible = FolosesteObservatii;
            ObservatiiColumn.Visible = FolosesteObservatii;
            observatiiL.Visible = FolosesteObservatii; 
            #endregion

            GestiuneaStocurilor = FSRow.GestiuneaStocurilor;
            ProductieActivata = FSRow.Productie;

            ValoareTotalaCuAdaosColumn.Visible = DocumenteIntrare && FolosesteValoareTotalaCuAdaos;
            totalCuAdaosTB.Visible = DocumenteIntrare && FolosesteValoareTotalaCuAdaos;
            TotalGeneralAdaosL.Visible = DocumenteIntrare && FolosesteValoareTotalaCuAdaos;
            if (GestiuneaStocurilor)
                DepartamentL.Text = "Gestiune:";

            Valuta = FSRow.Valuta;

            codValutaL.Visible = Valuta;
            codValutaCB.Visible = Valuta;
            cursValutarNUD.Visible = Valuta;
            leiL.Visible = Valuta;
            ValoareUnitaraValutaColumn.Visible = Valuta;

            ValutaImplicita = FSRow.ValutaImplicita;

            BancaImplicita = FSRow.IDBancaImplicita;

            if (!FolosesteVarianta)           
                IDArticolColumn.Width += 50;

            if (!FolosesteDataLivrare)
                IDArticolColumn.Width += 50;

            CotaTVAImplicita = FSRow.CotaTVAImplicita;
            eSRPDataSet.Documente.CotaTVAColumn.DefaultValue = CotaTVAImplicita;
            eSRPDataSet.DocumenteDetaliu.CotaTVAColumn.DefaultValue = CotaTVAImplicita;

            AfiseazaProprietarDocument = FSRow.AfiseazaProprietarDocument;

            ParteneriProprii = FSRow.ParteneriProprii;

            AvizExpeditieCuTVA = FSRow.AvizExpeditieCuTVA;

            eSRPDataSet.Documente.AreDocGestStocColumn.DefaultValue = FSRow.AreDocGestStoc;

            #region Verificare si transfer pentru parteneri proprii
            ///verifica daca sunt documente spre alti parteneri 
            ///
            SqlCommand comm = new SqlCommand("[fares_ParteneriProprii]", wConn);
            if (ParteneriProprii)
            {
                comm.CommandType = CommandType.StoredProcedure;
                comm.Parameters.Add(new SqlParameter("@CodUnitate", ModuleInfo.CodUnitate));
                try
                {
                    int cate = Convert.ToInt32(comm.ExecuteScalar());
                }
                catch (Exception Ex)
                {
                    MyTrace("Eroare fares_ParteneriProprii: " + Ex.Message);
                }
            }
            
            #endregion     

            #region determina regimul fiscal implicit
            comm.CommandText = "SELECT MIN(IDRegimFiscal) FROM RegimFiscal WHERE Vizibil=1 AND TipOperatie LIKE '%" +
                    (DocumenteIntrare ? "I" : "O") + "%'";
            comm.CommandType = CommandType.Text;
            Object retu = comm.ExecuteScalar();
            Int32 idRegFis = 0;
            if(retu!=null && retu!=DBNull.Value)
                idRegFis = Convert.ToInt32(retu);
            eSRPDataSet.Documente.IDRegimFiscalColumn.DefaultValue = idRegFis;
            eSRPDataSet.DocumenteDetaliu.IDRegimFiscalColumn.DefaultValue = idRegFis; 
            #endregion

            #region Verifica existenta cel putin a unui partener
            while (CodPartenerPentruBC == 0)
            {
                comm.CommandText = "SELECT MIN(IDPartener) FROM [Parteneri] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                comm.CommandType = CommandType.Text;
                retu = comm.ExecuteScalar();
                if (retu != null && retu != DBNull.Value)
                {
                    CodPartenerPentruBC = Convert.ToInt64(retu);
                    break;
                }
                else
                {
                    MessageBox.Show("Nu este posibila adaugarea nici unui document fara existenta a cel putin\nunui partener!");
                    FrmMainMdi frm = this.MdiParent as FrmMainMdi;
                    Assembly asm = frm.GetModule("erpforms");
                    if (asm == null)
                        return;
                    String numeClasa = "ERPForms.PartenerFrm";
                    Type mModule = asm.GetType(numeClasa);

                    if (mModule != null)
                    {
                        FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                            new object[] { ModuleInfo, true }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;
                        mModule.InvokeMember("DenumirePartener", BindingFlags.SetProperty, null, newFrm, new object[] { "PARTENER NOU" });

                        newFrm.ShowDialog();

                    }
                }
            }
            #endregion

            eSRPDataSet.DocumenteDetaliu.TVAIncasareColumn.DefaultValue = FSRow.TVAIncasareImplicit;

            if (!AfiseazaProprietarDocument)
            {
                userIdCB.Visible = false;
                userIdL.Visible = false;
            }

            if (LunaCurenta == 0)
            {
                MessageBox.Show("Modulul Parteneri nu a fost configurat corect (Luna curenta=0). \nVa rugam sa-l configurati!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                return;
            }

            ///daca este in perioada curenta
            if (ModuleInfo.AnArhiva == String.Empty)
            {
                //documenteBindingSource.Filter = "[DataDoc] <= '" + dataDocDTP.MaxDate.Year.ToString() + "-" + dataDocDTP.MaxDate.Month.ToString() + "-" + dataDocDTP.MaxDate.Day.ToString() + "'";
                //dataDocDTP.MaxDate = new DateTime(AnulCurent, LunaCurenta, 1).AddMonths(1).AddDays(-1);
                //eSRPDataSet.Documente.DataDocColumn.DefaultValue = dataDocDTP.MaxDate;
                //SetInfoLunaAnul(LunaCurenta.ToString() + "," + AnulCurent.ToString());
            }

            String afis = GetSetariLocale(wConn, "RFIM", "0", ModuleInfo.CodUnitate);

            ///verifica daca exista regimul printre regimurile selectate
            comm.CommandText = "SELECT IDRegimFiscal FROM RegimFiscal WHERE Vizibil=1 AND TipOperatie LIKE '%" +
                   (DocumenteIntrare ? "I" : "O") + "%' AND IDRegimFiscal=" + afis;
            comm.CommandType = CommandType.Text;
            retu = comm.ExecuteScalar();
            if (retu!=null && (Convert.ToInt16(retu) == Convert.ToInt16(afis)))
            {
                eSRPDataSet.Documente.IDRegimFiscalColumn.DefaultValue = Convert.ToInt16(afis);
                eSRPDataSet.DocumenteDetaliu.IDRegimFiscalColumn.DefaultValue = Convert.ToInt16(afis);
            }
            
                comm.CommandText = "SELECT TOP 1 CodValuta FROM [Valuta] WHERE MonedaImplicita=1";
                comm.CommandType = CommandType.Text;
                try
                {
                    retu = comm.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    TrateazaExceptie(ex);
                    return;
                }


                while (retu == null)
                {
                    FrmMainMdi frm = this.MdiParent as FrmMainMdi;
                    Assembly asm = frm.GetModule("erpforms");
                    String numeClasa = "ERPForms.ValuteFrm";
                    Type mModule = asm.GetType(numeClasa);

                    if (mModule != null)
                    {
                        FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                            new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;
                        newFrm.Text = "Va rugam setati moneda implicita!";
                        newFrm.ShowDialog();
                        retu = comm.ExecuteScalar();
                    }
                }

                MonedaImplicita = Convert.ToInt16(retu);
                codValutaCB.SelectedValue = ValutaImplicita;
                eSRPDataSet.Documente.CodValutaColumn.DefaultValue = ValutaImplicita;

            eSRPDataSet.Documente.CursValutarColumn.DefaultValue = 0;
        }

        override public void toolStripLabelAnLuna_Click(object sender, EventArgs e)
        {
            FaresSetupFrm frm = new FaresSetupFrm(this.ModuleInfo);
            frm.ShowDialog();
            ///actualizare unitate la copi
            foreach (Form frmChild in this.MdiParent.MdiChildren)
            {
                //if (frmChild != this)
                ((StudioForm)frmChild).SetCurentMonth(ModuleInfo.CodUnitate);
            }
        }

        override public void SetCurentMonth(short vCodUnitate)
        {
            SqlConnection con = DeschideConexiune(workConnString);
            Setup(con);
            InchideConexiune(con);
        }

        private void ActualizeazaValoareaTotalaLinie(Decimal val, Int32 tipDoc, int RowIndex, Decimal valValuta = -1)
        {
            if(documenteBindingSource.Current==null)
                return;
            DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                        as DataSets.ESRPDataSet.DocumenteRow;

            Decimal cantit = Decimal.Zero;
            if (docDetaliuDGV[CantitateColumn.Index, RowIndex].Value != DBNull.Value)
                cantit = Convert.ToDecimal(docDetaliuDGV[CantitateColumn.Index, RowIndex].Value);

            if (valValuta != -1)
            {
                val = Decimal.Round(valValuta *(((rd.IDTipDocument==9 || rd.IDTipDocument==12) && ComenziFaraPret)?1:rd.CursValutar),2);
                docDetaliuDGV[ValoareUnitaraColumn.Index, RowIndex].Value = val;
            }
            Decimal nVal = Decimal.Round(val * cantit, 2);


            Boolean modificat = false;
            if ((docDetaliuDGV[ValoareTotalaColumn.Index,RowIndex].Value == DBNull.Value) || (Convert.ToDecimal(docDetaliuDGV[ValoareTotalaColumn.Index, RowIndex].Value) != nVal))
            {
                docDetaliuDGV[ValoareTotalaColumn.Index, RowIndex].Value = nVal;
                modificat = true;
            }
            short regim_fis = 0;
            if (docDetaliuDGV[regimFiscalColumn.Index, RowIndex].Value != DBNull.Value)
                regim_fis = Convert.ToInt16(docDetaliuDGV[regimFiscalColumn.Index,RowIndex].Value);

            modificat |= CalculeazaTVALinie(RowIndex, nVal, regim_fis, tipDoc);

            if (modificat == true)
            {
                if (docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, RowIndex].Visible &&
                            (docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, RowIndex].Value == DBNull.Value || Convert.ToDecimal(docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, RowIndex].Value) == Decimal.Zero))
                {
                    Decimal valTVA = Decimal.Zero;
                    if (docDetaliuDGV[ValoareTVAColumn.Index, RowIndex].Value != DBNull.Value)
                        valTVA = Convert.ToDecimal(docDetaliuDGV[ValoareTVAColumn.Index, RowIndex].Value != DBNull.Value);
                    docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, RowIndex].Value = nVal + valTVA;
                }

                if (documenteBindingSource.Current != null)
                {
                    SeteazaTotalDocument(rd.IDTipDocument);
                }


            }
        }

        private void ActualizeazaValoareaTotalaLinieBindingSource(Decimal val, Int32 tipDoc, ref DataSets.ESRPDataSet.DocumenteDetaliuRow ddr, Decimal valValuta = -1)
        {
            if (documenteBindingSource.Current == null)
                return;
            DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                        as DataSets.ESRPDataSet.DocumenteRow;

            if (valValuta != -1)
            {
                val = Decimal.Round(valValuta * (((rd.IDTipDocument == 9 || rd.IDTipDocument == 12) && ComenziFaraPret) ? 1 : rd.CursValutar), 2);
                ddr.ValoareUnitara = val;
            }
            Decimal nVal = Decimal.Round(val * ddr.Cantitate, 2);     
            ddr.ValoareTotala = nVal;
   
            CalculeazaTVALinieBindingSource(ref ddr, nVal, ddr.IDRegimFiscal, tipDoc);

            if (ddr.ValoareTotalaCuAdaos == Decimal.Zero)
            {
                ddr.ValoareTotalaCuAdaos = nVal + ddr.ValoareTVA;
            }

            if (documenteBindingSource.Current != null)
            {
                SeteazaTotalDocument(rd.IDTipDocument);
            }
   
        }

        private Dictionary<int,String> OldArticolDenumire = new Dictionary<int,string>();
        private void docDetaliuDGV_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            ///se verifica existenta articolului selectat
            ///
            if (articoleBindingSource.Current == null && e.ColumnIndex > IDArticolColumn.Index)
            {
                MessageBox.Show("Va rugam sa selectati articolul inainte de a completa celelalte campuri ale liniei!",
                        "Eroare",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Hand);
                
            }

            Int32 tipDoc = 0;
            if(tipDocumentCB.SelectedValue!=null)
                tipDoc= Convert.ToInt32(tipDocumentCB.SelectedValue);

            #region Validare Cod Articol
            if (e.ColumnIndex == IDCodArticolColumn.Index)
            {
                DataGridViewComboBoxCell cb = docDetaliuDGV.CurrentCell as DataGridViewComboBoxCell;
                if (ArticoleSearchBS.Find("CodArticol", e.FormattedValue) < 0)
                {
                    //valoarea completata nu exista in lista
                    MessageBoxFrm mbt = new MessageBoxFrm("Selectie", "Articolul cu codul " + e.FormattedValue.ToString() + " inexistent in nomenclator. Doriti selectarea unui alt articol sau adaugarea lui?", "",MessageBoxFrm.ImaginiMB.IntrebareIcon, null);
                    mbt.AddButton("Adaugare", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.AddButton("Selectie", 70, mbt.MessageBoxFrm_Click_No);
                    mbt.AddButton("Renuntare", 70, mbt.MessageBoxFrm_Click_Cancel);
                    DialogResult retD = mbt.ShowDialog();
                    if (retD == DialogResult.Yes)
                    {
                        ArticoleCardFrm frm = new ArticoleCardFrm(ModuleInfo, -1);
                        frm.CodArticol = e.FormattedValue.ToString();
                        frm.ShowDialog();
                        if (frm.NoRecUpdated != 0)
                        {
                            articoleTableAdapter.Connection = DeschideConexiune(workConnString);
                            articoleTableAdapter.Fill(eSRPDataSet.Articole, ModuleInfo.CodUnitate);
                            InchideConexiune(articoleTableAdapter.Connection);
                        }
                    }
                    if (retD == DialogResult.No) //rezumat
                    {
                        ArticoleRezumatFrm frm = new ArticoleRezumatFrm(ModuleInfo, -1);
                        //frm.CodArticol = e.FormattedValue.ToString();
                        frm.SelectionAddOn = true;
                        frm.ShowDialog();
                        if (frm.NoRecUpdated != 0)
                        {
                            articoleTableAdapter.Connection = DeschideConexiune(workConnString);
                            articoleTableAdapter.Fill(eSRPDataSet.Articole, ModuleInfo.CodUnitate);
                            InchideConexiune(articoleTableAdapter.Connection);
                        }
                    }
                }
            } 
            #endregion

            #region Validare Denumire Articol
            if (e.ColumnIndex == IDArticolColumn.Index)
            {
                DataSets.ESRPDataSet.DocumenteRow docRow = ((DataRowView)documenteBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteRow;
                if (OldArticolDenumire.ContainsKey(e.RowIndex) &&
                    OldArticolDenumire[e.RowIndex] == docDetaliuDGV[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString())
                {
                    if (FolosesteVarianta)
                    {
                        Int32 idArt = -1;
                        if (docDetaliuDGV[e.ColumnIndex, e.RowIndex].Value != DBNull.Value)
                            idArt = Convert.ToInt32(docDetaliuDGV[e.ColumnIndex, e.RowIndex].Value);
                        else
                            idArt = Convert.ToInt32(e.FormattedValue);
                        DataSets.ESRPDataSet.ArticoleRow arr = ((DataRowView)articoleBindingSource.Current).Row as DataSets.ESRPDataSet.ArticoleRow;
                        String filt = "IDArticol=" + idArt.ToString();
                        if (articoleVarianteBindingSource.Filter != filt)
                        {
                            articoleVarianteBindingSource.Filter = filt;
                            docDetaliuDGV[IDVariantaArticolColumn.Index, e.RowIndex].ReadOnly = articoleVarianteBindingSource.Count == 0;
                        }
                        //21.08.2012 - se inlocuieste pretul produsului daca este diferit de 0
                        if (!arr.EsteServiciu)
                            if ((tipDoc == 12) && (docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value == DBNull.Value ||
                                    Convert.ToDecimal(docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value) != arr.PretVanzare) && arr.PretVanzare != Decimal.Zero)
                                docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value = arr.PretVanzare;
                    }
                    return;
                }
                if (!OldArticolDenumire.ContainsKey(e.RowIndex))
                    OldArticolDenumire.Add(e.RowIndex, docDetaliuDGV[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString());
                else
                    OldArticolDenumire[e.RowIndex] = docDetaliuDGV[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString();
                //if (docDetaliuDGV.CurrentCell == null || docDetaliuDGV.CurrentCell.GetType() != typeof(DataGridViewComboBoxCell))
                //    return;
                //DataGridViewComboBoxCell cb = docDetaliuDGV.CurrentCell as DataGridViewComboBoxCell;
                String denCauta = e.FormattedValue.ToString().Trim().ToUpper();
                int pozGasita = ArticoleSearchBS.Find("Denumire", denCauta);
                if (pozGasita < 0)
                {
                    //valoarea completata nu exista in lista
                    MessageBoxFrm mbt = new MessageBoxFrm("Selectie", "Articolul cu denumirea " + denCauta + " este inexistent in nomenclator. Doriti selectarea unui alt articol sau adaugarea lui?", "",MessageBoxFrm.ImaginiMB.IntrebareIcon, null);
                    mbt.AddButton("Adaugare", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.AddButton("Selectie", 70, mbt.MessageBoxFrm_Click_No);
                    mbt.AddButton("Renuntare", 70, mbt.MessageBoxFrm_Click_Cancel);
                    DialogResult retD = mbt.ShowDialog();
                    String ValSel = String.Empty;
                    Int32 IDUMSel = 0;
                    Decimal PretVanzare = decimal.Zero;
                    Decimal PretVanzareValuta = decimal.Zero;
                    Decimal CotaTVAArticol = CotaTVAImplicita;
                    String ArtAlArticol = String.Empty;
                    if (retD == DialogResult.Yes)
                    {
                        ArticoleCardFrm frm = new ArticoleCardFrm(ModuleInfo, -1);
                        if (e.FormattedValue != null)
                            frm.DenumireArticol = denCauta;
                        frm.ShowDialog();
                        if (frm.currentRow != null)
                        {
                            ValSel = frm.currentRow.Row["IDArticol"].ToString().ToUpper();
                            IDUMSel = Convert.ToInt32(frm.currentRow.Row["IDUnitateMasura"]);
                            if (Valuta)
                            {
                                if (docRow.CodValuta != MonedaImplicita)
                                    PretVanzareValuta = Convert.ToDecimal(frm.currentRow.Row["PretVanzareValuta"]);
                                else
                                    PretVanzare = Convert.ToDecimal(frm.currentRow.Row["PretVanzare"]);
                            }
                            else
                                PretVanzare = Convert.ToDecimal(frm.currentRow.Row["PretVanzare"]);
                            if (FolosesteTVAArticol)
                                CotaTVAArticol = Convert.ToDecimal(frm.currentRow.Row["CotaTVA"]);
                            if (Bugetara)
                                ArtAlArticol = frm.currentRow.Row["ArtAl"].ToString();
                        }
                        //se incarca lista de articole indiferent de situatie
                    }
                    if (retD == DialogResult.No) //rezumat
                    {
                        ArticoleRezumatFrm frm = new ArticoleRezumatFrm(ModuleInfo, -1);
                        frm.SelectionAddOn = true;
                        frm.DenumireArticol = denCauta;
                        frm.ShowDialog();
                        if (frm.currentRow != null)
                        {
                            ValSel = frm.currentRow.Row["IDArticol"].ToString().ToUpper();
                            IDUMSel = Convert.ToInt32(frm.currentRow.Row["IDUnitateMasura"]);
                            if (Valuta)
                            {
                                if (docRow.CodValuta != MonedaImplicita)
                                    PretVanzareValuta = Convert.ToDecimal(frm.currentRow.Row["PretVanzareValuta"]);
                                else
                                    PretVanzare = Convert.ToDecimal(frm.currentRow.Row["PretVanzare"]);
                            }
                            else
                                PretVanzare = Convert.ToDecimal(frm.currentRow.Row["PretVanzare"]);
                            if (FolosesteTVAArticol)
                                CotaTVAArticol = Convert.ToDecimal(frm.currentRow.Row["CotaTVA"]);
                            if (Bugetara)
                                ArtAlArticol = frm.currentRow.Row["ArtAl"].ToString();
                        }

                    }
                    articoleTableAdapter.Connection = DeschideConexiune(workConnString);
                    articoleTableAdapter.Fill(eSRPDataSet.Articole, ModuleInfo.CodUnitate);
                    articoleBindingSource.ResetBindings(false);
                    if (FolosesteVarianta)
                    {
                        articoleVarianteTableAdapter.Connection = articoleTableAdapter.Connection;
                        //face refresh pe varinate
                        articoleVarianteTableAdapter.Fill(eSRPDataSet.ArticoleVariante);
                        articoleVarianteBindingSource.ResetBindings(false);
                        String filt = "IDArticol=" + ValSel.ToString();
                        if (articoleVarianteBindingSource.Filter != filt)
                        {
                            articoleVarianteBindingSource.Filter = filt;
                            if (articoleVarianteBindingSource.Count == 0)
                            {
                                docDetaliuDGV.CurrentCell.ReadOnly = articoleVarianteBindingSource.Count == 0;
                            }

                        }
                    }
                    InchideConexiune(articoleTableAdapter.Connection);
                    docDetaliuDGV[e.ColumnIndex, e.RowIndex].Value = ValSel;
                    docDetaliuDGV[IDUnitateMasuraColumn.Index, e.RowIndex].Value = IDUMSel;
                    if (Valuta)
                    {
                        if (docRow.CodValuta != MonedaImplicita)
                            docDetaliuDGV[ValoareUnitaraValutaColumn.Index, e.RowIndex].Value = PretVanzareValuta;
                        else
                            docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value = PretVanzare;
                    }
                    else
                        docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value = PretVanzare;
                    if (FolosesteTVAArticol)
                        docDetaliuDGV[CotaTVAColumn.Index, e.RowIndex].Value = CotaTVAArticol;
                    if (Bugetara)
                        docDetaliuDGV[ArtAlColumn.Index, e.RowIndex].Value = ArtAlArticol;

                }
                else
                {
                    ArticoleSearchBS.Position = pozGasita;
                    DataSets.ESRPDataSet.ArticoleRow artr = ((DataSets.ESRPDataSet.ArticoleRow)((DataRowView)ArticoleSearchBS.Current).Row);
                    if (Convert.ToInt16(docDetaliuDGV[IDUnitateMasuraColumn.Index, e.RowIndex].Value) != artr.IDUnitateMasura)
                        docDetaliuDGV[IDUnitateMasuraColumn.Index, e.RowIndex].Value = artr.IDUnitateMasura;
                    //21.08.2012 - se inlocuieste pretul produsului daca este diferit de 0
                    if (!artr.EsteServiciu)
                    {
                        if (!DocumenteIntrare)
                        {
                            if (Valuta)
                            {
                                if (docRow.CodValuta != MonedaImplicita)
                                {
                                    if ((docDetaliuDGV[ValoareUnitaraValutaColumn.Index, e.RowIndex].Value == DBNull.Value ||
                                        Convert.ToDecimal(docDetaliuDGV[ValoareUnitaraValutaColumn.Index, e.RowIndex].Value) != artr.PretVanzareValuta) && artr.PretVanzareValuta != Decimal.Zero)
                                        docDetaliuDGV[ValoareUnitaraValutaColumn.Index, e.RowIndex].Value = artr.PretVanzareValuta;
                                }
                                else
                                {
                                    if ((docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value == DBNull.Value ||
                                        Convert.ToDecimal(docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value) != artr.PretVanzare) && artr.PretVanzare != Decimal.Zero)
                                        docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value = artr.PretVanzare;
                                }
                            }
                            else
                            {
                                if ((docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value == DBNull.Value ||
                                    Convert.ToDecimal(docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value) != artr.PretVanzare) && artr.PretVanzare != Decimal.Zero)
                                    docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value = artr.PretVanzare;
                            }
                        }
                    }
                    if (FolosesteTVAArticol)
                        if (Convert.ToDecimal(docDetaliuDGV[CotaTVAColumn.Index, e.RowIndex].Value) != artr.CotaTVA)
                            docDetaliuDGV[CotaTVAColumn.Index, e.RowIndex].Value = artr.CotaTVA;

                    if (Bugetara && !artr.IsArtAlNull())
                        if ((docDetaliuDGV[ArtAlColumn.Index, e.RowIndex].Value == DBNull.Value ||
                            docDetaliuDGV[ArtAlColumn.Index, e.RowIndex].Value.ToString() != artr.ArtAl) && !String.IsNullOrEmpty(artr.ArtAl))
                            docDetaliuDGV[ArtAlColumn.Index, e.RowIndex].Value = artr.ArtAl;

                    if (FolosesteVarianta)
                    {
                        String filt = "IDArticol=" + artr.IDArticol.ToString();
                        if (articoleVarianteBindingSource.Filter != filt)
                        {
                            articoleVarianteBindingSource.Filter = filt;
                            if (articoleVarianteBindingSource.Count == 0)
                            {
                                docDetaliuDGV.CurrentCell.ReadOnly = articoleVarianteBindingSource.Count == 0;
                            }

                        }
                    }


                }
            }
            
            #endregion

            #region Validare Varianta Articol
            if (e.ColumnIndex == IDVariantaArticolColumn.Index)
            {
                ComboBox cb = docDetaliuDGV.EditingControl as ComboBox;
                if (cb != null && cb.Items.Count == 0)
                {
                    e.Cancel = false;
                    return;
                }
                if (cb != null && cb.SelectedItem != null)
                {
                    DataSets.ESRPDataSet.ArticoleVarianteRow arr = ((DataRowView)cb.SelectedItem).Row as DataSets.ESRPDataSet.ArticoleVarianteRow;
                    docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value = arr.PretVanzare;
                    ActualizeazaValoareaTotalaLinie(arr.PretVanzare, tipDoc, e.RowIndex);
                }
                return;
            } 
            #endregion

            #region Validare Articol Aliniat pentru unitati bugetare
            if (e.ColumnIndex == ArtAlColumn.Index)
            {
                String val = String.Empty;
                try
                {
                    val = e.FormattedValue.ToString();
                }
                catch { }

                if (val == String.Empty && Bugetara)
                {
                    MessageBox.Show("Cantitatea trebuie sa fie o valoare nenula!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    e.Cancel = true;
                }
            } 
            #endregion

            #region Validare Cantitate
            if (e.ColumnIndex == CantitateColumn.Index)
            {
                Decimal val = Decimal.Zero;
                try
                {
                    val = Convert.ToDecimal(e.FormattedValue);
                }
                catch { }

                if (val == Decimal.Zero)
                {
                    MessageBox.Show("Cantitatea trebuie sa fie o valoare nenula!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    e.Cancel = true;
                }
                else
                {
                    if (docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value != DBNull.Value)
                    {
                        Decimal nVal = Decimal.Round(val * Convert.ToDecimal(docDetaliuDGV[ValoareUnitaraColumn.Index, e.RowIndex].Value), 2);
                        Boolean modificat = false;
                        if ((docDetaliuDGV[ValoareTotalaColumn.Index, e.RowIndex].Value == DBNull.Value) || (Convert.ToDecimal(docDetaliuDGV[ValoareTotalaColumn.Index, e.RowIndex].Value) != nVal))
                        {
                            docDetaliuDGV[ValoareTotalaColumn.Index, e.RowIndex].Value = nVal;


                            ///daca se modifica valoare schimbam si totalul
                            modificat = true;
                        }
                        modificat |= CalculeazaTVALinie(e.RowIndex, Convert.ToDecimal(docDetaliuDGV[ValoareTotalaColumn.Index, e.RowIndex].Value),
                            Convert.ToInt16(docDetaliuDGV[regimFiscalColumn.Index, e.RowIndex].Value), tipDoc);
                        if (modificat == true)
                        {
                            if (documenteBindingSource.Current != null)
                            {
                                DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                                    as DataSets.ESRPDataSet.DocumenteRow;
                                SeteazaTotalDocument(rd.IDTipDocument);
                            }

                            if (docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Visible &&
                                (docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Value == DBNull.Value || Convert.ToDecimal(docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Value) == Decimal.Zero))
                                docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Value = Convert.ToDecimal(docDetaliuDGV[ValoareTotalaColumn.Index, e.RowIndex].Value) +
                                    Convert.ToDecimal(docDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value);
                        }
                    }


                }
                return;
            }
            
            #endregion

            #region Validare Valoare Unitara

            if (e.ColumnIndex == ValoareUnitaraColumn.Index)
            {
                Decimal val = Decimal.Zero;
                try
                {
                    MyTrace("Valoare unitara rd:" + e.FormattedValue.ToString());
                    if (!decimal.TryParse(e.FormattedValue.ToString(), out val) || (val < 0) || (!FSRow.PermitePretZero && val==0))
                    {
                       
                        MessageBoxFrm mbt = new MessageBoxFrm("Atentie", "Prețul unitar trebuie să fie o valoare pozitivă! Doriti selectarea unui preț pentru articolul curent sau definirea unuia nou?", "",MessageBoxFrm.ImaginiMB.IntrebareIcon, null);
                        mbt.AddButton("Adăugare", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.AddButton("Selecție", 70, mbt.MessageBoxFrm_Click_No);
                        mbt.AddButton("Renunțare", 70, mbt.MessageBoxFrm_Click_Cancel);
                        DialogResult retD = mbt.ShowDialog();

                        if (retD == System.Windows.Forms.DialogResult.Cancel)
                        {
                            e.Cancel = true;
                            return;
                        }
                        if (retD == System.Windows.Forms.DialogResult.No)
                        {
                            if (docDetaliuDGV[e.ColumnIndex, e.RowIndex].IsInEditMode)
                                docDetaliuDGV.EditingControl.Text = SelecteazaPretulVanzarePartener(e.RowIndex, e.ColumnIndex).ToString();
                            else
                                docDetaliuDGV[e.ColumnIndex, e.RowIndex].Value = SelecteazaPretulVanzarePartener(e.RowIndex, e.ColumnIndex);
                            return;
                        }
                        if (retD == System.Windows.Forms.DialogResult.Yes)
                        {
                            RezumatArticole(sender,null);
                            e.Cancel = true;
                            return;
                        }
                    }

                }
                catch { }

                if (Convert.ToDecimal(docDetaliuDGV[e.ColumnIndex, e.RowIndex].Value) != Convert.ToDecimal(e.FormattedValue))
                    docDetaliuDGV[e.ColumnIndex, e.RowIndex].Value = Convert.ToDecimal(e.FormattedValue);
                ActualizeazaValoareaTotalaLinie(val, tipDoc, e.RowIndex);


                return;
            }
            
            #endregion

            #region Validare Valoare Unitara valuta
            if (e.ColumnIndex == ValoareUnitaraValutaColumn.Index)
            {
                Decimal val = Decimal.Zero;
                try
                {
                    MyTrace("Valoare unitara valuta rd:" + e.FormattedValue.ToString());
                    if (!decimal.TryParse(e.FormattedValue.ToString(), out val) || val <= 0)
                    {
                        
                        MessageBoxFrm mbt = new MessageBoxFrm("Atentie", "Pretul unitar valuta trebuie sa fie o valoare pozitiva!. Doriti selectarea unui pret pentru articolul curent sau definirea unuia nou?", "",MessageBoxFrm.ImaginiMB.ExclamareIcon, null);
                        mbt.AddButton("Adaugare", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.AddButton("Selectie", 70, mbt.MessageBoxFrm_Click_No);
                        mbt.AddButton("Renuntare", 70, mbt.MessageBoxFrm_Click_Cancel);
                        DialogResult retD = mbt.ShowDialog();

                        if (retD == System.Windows.Forms.DialogResult.Cancel)
                        {
                            e.Cancel = true;
                            return;
                        }
                        if (retD == System.Windows.Forms.DialogResult.No)
                        {
                            if (docDetaliuDGV[e.ColumnIndex, e.RowIndex].IsInEditMode)
                                docDetaliuDGV.EditingControl.Text = SelecteazaPretulVanzarePartener(e.RowIndex, e.ColumnIndex).ToString();
                            else
                                docDetaliuDGV[e.ColumnIndex, e.RowIndex].Value = SelecteazaPretulVanzarePartener(e.RowIndex, e.ColumnIndex);
                            return;
                        }
                        if (retD == System.Windows.Forms.DialogResult.Yes)
                        {
                            RezumatArticole(sender, null);
                            e.Cancel = true;
                            return;
                        }
                    }

                }
                catch { }

                if (Convert.ToDecimal(docDetaliuDGV[e.ColumnIndex, e.RowIndex].Value) != Convert.ToDecimal(e.FormattedValue))
                    docDetaliuDGV[e.ColumnIndex, e.RowIndex].Value = Convert.ToDecimal(e.FormattedValue);
                ActualizeazaValoareaTotalaLinie(Decimal.Zero, tipDoc, e.RowIndex, val);


                return;
            } 
            #endregion

            #region Validare Cota TVA
            if (e.ColumnIndex == CotaTVAColumn.Index)
            {
                Decimal val = Decimal.Zero;
                try
                {
                    val = Convert.ToDecimal(e.FormattedValue);
                }
                catch { }

                if (val < Decimal.Zero)
                {
                    MessageBox.Show("Cota TVA trebuie sa fie o valoare pozitiva sau zero!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    e.Cancel = true;
                    return;
                }
                Int16 _regFisc = Convert.ToInt16(docDetaliuDGV[regimFiscalColumn.Index, e.RowIndex].Value);
                if (val != Decimal.Zero && (RegimuriTVAZero.Contains(_regFisc)))
                {
                    MessageBox.Show("Cota TVA trebuie sa  fie zero pentru regimul selectat!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    e.Cancel = true;
                    return;
                }

                if (docDetaliuDGV[ValoareTotalaColumn.Index, e.RowIndex].Value != DBNull.Value)
                {
                    Decimal ValoareTotalaDec = Convert.ToDecimal(docDetaliuDGV[ValoareTotalaColumn.Index, e.RowIndex].Value);
                    Boolean modificat = CalculeazaTVALinie(e.RowIndex, ValoareTotalaDec,
                        Convert.ToInt16(docDetaliuDGV[regimFiscalColumn.Index, e.RowIndex].Value), tipDoc);
                    if (modificat)
                    {
                        Decimal valTVA = Decimal.Zero;
                        if (docDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value != DBNull.Value)
                            valTVA = Convert.ToDecimal(docDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value != DBNull.Value);
                        if (docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Visible &&
                                (docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Value == DBNull.Value || Convert.ToDecimal(docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Value) == Decimal.Zero))
                            docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Value = ValoareTotalaDec + valTVA;
                        if (documenteBindingSource.Current != null)
                        {
                            DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                                as DataSets.ESRPDataSet.DocumenteRow;
                            SeteazaTotalDocument(rd.IDTipDocument);
                        }

                    }
                }
                return;
            }
            
            #endregion

            #region Validare Valoare Totala Cu Adaos
            if (e.ColumnIndex == ValoareTotalaCuAdaosColumn.Index)
            {
                if (documenteBindingSource.Current != null)
                {
                    DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                        as DataSets.ESRPDataSet.DocumenteRow;
                    SeteazaTotalDocument(rd.IDTipDocument);
                }

                return;
            } 
            #endregion

            #region Validare Valoare TVA
            if (e.ColumnIndex == ValoareTVAColumn.Index)
            {
                Decimal val = Decimal.Zero;
                try
                {
                    val = Convert.ToDecimal(e.FormattedValue);
                }
                catch { }

                /*if (val < Decimal.Zero)
                {
                    MessageBox.Show("Valoarea TVA trebuie sa fie o valoare pozitiva sau zero!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    e.Cancel = true;
                    return;
                }*/
                Int16 _regFisc = Convert.ToInt16(docDetaliuDGV[regimFiscalColumn.Index, e.RowIndex].Value);
                if (val != Decimal.Zero && (RegimuriTVAZero.Contains(_regFisc)))
                {
                    MessageBox.Show("Valoarea TVA trebuie sa  fie zero pentru regimul selectat!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    e.Cancel = true;
                    return;
                }

                if (docDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value == DBNull.Value || (Convert.ToDecimal(docDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value) != val))
                {
                    docDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value = val;
                    #region 2012.07.08 Modificare cotei corespunzator valorii TVA cu interogare
                    ///daca se modifica TVA atunci modifica si Cota TVA
                    ///
                    Decimal cotaActuala = Convert.ToDecimal(docDetaliuDGV[CotaTVAColumn.Index, e.RowIndex].Value);
                    Decimal valoareTotalaActuala = Decimal.Zero;
                    if (docDetaliuDGV[ValoareTotalaColumn.Index, e.RowIndex].Value != DBNull.Value)
                    {
                        valoareTotalaActuala = Convert.ToDecimal(docDetaliuDGV[ValoareTotalaColumn.Index, e.RowIndex].Value);
                        Decimal nouaCota = Decimal.Round((val * 100) / valoareTotalaActuala);
                        if (nouaCota != cotaActuala)
                        {
                            MessageBoxFrm mbt = new MessageBoxFrm("Modificare", "Ati modificat valoare TVA la " + val.ToString() + ". Doriti modificarea cotei TVA la " + nouaCota.ToString() + "?", "",MessageBoxFrm.ImaginiMB.IntrebareIcon, null);
                            mbt.AddButton("Modificare", 70, mbt.MessageBoxFrm_Click_Yes);
                            mbt.AddButton("Pastrare", 70, mbt.MessageBoxFrm_Click_No);
                            mbt.AddButton("Renuntare", 70, mbt.MessageBoxFrm_Click_Cancel);
                            DialogResult retD = mbt.ShowDialog();
                            if (retD == System.Windows.Forms.DialogResult.Yes)
                                docDetaliuDGV[CotaTVAColumn.Index, e.RowIndex].Value = nouaCota;
                        }
                    }
                    #endregion

                    if (docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Visible &&
                                (docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Value == DBNull.Value || Convert.ToDecimal(docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Value) == Decimal.Zero))
                    {
                        Decimal valtotcol = Decimal.Zero;
                        if (docDetaliuDGV[ValoareTotalaColumn.Index, e.RowIndex].Value != DBNull.Value)
                            valtotcol = Convert.ToDecimal(docDetaliuDGV[ValoareTotalaColumn.Index, e.RowIndex].Value);
                        docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Value = valtotcol +
                                        Convert.ToDecimal(docDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value);
                    }
                    if (documenteBindingSource.Current != null)
                    {
                        DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                            as DataSets.ESRPDataSet.DocumenteRow;
                        SeteazaTotalDocument(rd.IDTipDocument);
                    }

                }
                return;
            }
            
            #endregion

            #region Validare Regim Fiscal
            if (e.ColumnIndex == regimFiscalColumn.Index)
            {
                ComboBox regimCB = docDetaliuDGV.EditingControl as ComboBox;
                if (RegimuriTVAZero.Contains(Convert.ToInt16(regimCB.SelectedValue)))
                {
                    if (docDetaliuDGV[CotaTVAColumn.Index, e.RowIndex].Value != DBNull.Value)
                    {
                        Boolean modificat = false;
                        Decimal cotaTVA = Convert.ToDecimal(docDetaliuDGV[CotaTVAColumn.Index, e.RowIndex].Value);
                        if (cotaTVA != Decimal.Zero)
                        {
                            docDetaliuDGV[CotaTVAColumn.Index, e.RowIndex].Value = Decimal.Zero;
                            docDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value = Decimal.Zero;
                            modificat = true;
                        }
                        if (modificat)
                        {
                            Decimal valTVA = Decimal.Zero;
                            if (docDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value != DBNull.Value)
                                valTVA = Convert.ToDecimal(docDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value != DBNull.Value);
                            if (docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Visible &&
                                (docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Value == DBNull.Value || Convert.ToDecimal(docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Value) == Decimal.Zero))
                                docDetaliuDGV[ValoareTotalaCuAdaosColumn.Index, e.RowIndex].Value = Convert.ToDecimal(docDetaliuDGV[ValoareTotalaColumn.Index, e.RowIndex].Value) + valTVA;

                            if (documenteBindingSource.Current != null)
                            {
                                DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                                    as DataSets.ESRPDataSet.DocumenteRow;
                                SeteazaTotalDocument(rd.IDTipDocument);
                            }


                        }
                    }
                }
                return;
            } 
            #endregion
            
        }
        
        private void iDPartenerComboBox_Validated(object sender, EventArgs e)
        {
            String denPartener = PartenerCB.Text.Trim(),idPartSel = String.Empty;
            if (denPartener == String.Empty)
                return;
            searchPartenerBS.RemoveFilter();
            denPartener =  denPartener.Replace("'", "''");
            searchPartenerBS.Filter = "Denumire like '%" + denPartener + "%'";
            int nrPart = searchPartenerBS.Count;
            //iDPartenerCB.Text = denPartener;
            FrmMainMdi frm = this.MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("erpforms");
            if (asm == null)
                return;

            SqlConnection con = DeschideConexiune(workConnString);


            //while (nrPart != 1)
            //{
                if (nrPart == 0)
                {
                    String numeClasa = "ERPForms.PartenerFrm";
                    Type mModule = asm.GetType(numeClasa);

                    if (mModule != null)
                    {
                        FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                            new object[] { ModuleInfo,true }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;
                        mModule.InvokeMember("DenumirePartener", BindingFlags.SetProperty, null, newFrm, new object[] { denPartener });

                        newFrm.ShowDialog();
                        denPartener = newFrm.currentRow.Row["Denumire"].ToString().ToUpper();
                        idPartSel = newFrm.currentRow.Row["IDPartener"].ToString();
                        
                        //incarca furnizorii
                        fares_ParteneriCUITableAdapter.Connection = con;
                        fares_ParteneriCUITableAdapter.Fill(eSRPDataSet.fares_ParteneriCUI);
                        
                        PartenerCB.Text = denPartener;
                    }
                }
                else
                {
                    if (nrPart > 1)
                    {
                        String numeClasa = "ERPForms.ParteneriRezFrm";
                        Type mModule = asm.GetType(numeClasa);

                        if (mModule != null)
                        {
                            FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                                new object[] { ModuleInfo, -1 }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;
                            mModule.InvokeMember("DenumirePartener", BindingFlags.SetProperty, null, newFrm, new object[] { denPartener });
                            newFrm.SelectionAddOn = true;

                            if (newFrm.ShowDialog() == DialogResult.OK)
                            {
                                PartenerCB.Text = newFrm.selectedRow.Cells["denumireColumn"].Value.ToString();
                            }
                            else
                            {
                                PartenerCB.Text = String.Empty;
                            }
                            denPartener = PartenerCB.Text;
                            newFrm.Close();
                            if (newFrm != null)
                                newFrm.Dispose();
                        }
                    }
                    else
                    {
                        DataSets.ESRPDataSet.fares_ParteneriCUIRow partr = ((DataRowView)searchPartenerBS.Current).Row as DataSets.ESRPDataSet.fares_ParteneriCUIRow;
                        idPartSel = partr.IDPartener.ToString();
                    }
                }
                
            //}
                if (idPartSel != String.Empty)
                {
                    faresParteneriCUIBindingSource.Sort = "IDPartener";
                    faresParteneriCUIBindingSource.Position = faresParteneriCUIBindingSource.Find("IDPartener", Convert.ToInt32(idPartSel));
                }
                if (PartenerCB.SelectedItem != null)
                {
                    DataSets.ESRPDataSet.fares_ParteneriCUIRow pr = ((DataRowView)PartenerCB.SelectedItem).Row as DataSets.ESRPDataSet.fares_ParteneriCUIRow;
                    String mesaj = String.Empty;
                    if (!pr.IsContClientNull())
                        mesaj = "Cont client:" + pr.ContClient;
                    mesaj += "\nCont furnizor: " + pr.Cont;
                    toolTip1.SetToolTip(PartenerCB, mesaj);

                    ConditiiPB.Visible = !pr.IsConditiiDePlataNull() && pr.ConditiiDePlata != String.Empty;
                    if (!pr.IsConditiiDePlataNull())
                        toolTip1.SetToolTip(ConditiiPB, pr.ConditiiDePlata);
                    //toolTip1.SetToolTip(PartenerCB, pr.ConditiiDePlata);
                    DataRowView dr = documenteBindingSource.Current as DataRowView;
                    if (dr.IsNew || observatiiTB.Text == String.Empty)
                    {
                        if (!pr.IsConditiiDePlataNull())
                            observatiiTB.Text = pr.ConditiiDePlata;
                    }
                    articolePreturiBindingSource.Filter = "IDPartener=" + pr.IDPartener.ToString();
                    if (ProdusePeParteneri)
                    {
                        articoleTableAdapter.Connection = con;
                        articoleTableAdapter.FillByPartener(eSRPDataSet.Articole, pr.IDPartener);
                    }
                    
                }
                else
                {
                    ConditiiPB.Visible = false;
                    toolTip1.SetToolTip(ConditiiPB, String.Empty);
                }
            InchideConexiune(con);

        }

        private Decimal GetSum(int indexColoana, int idxColTVA, DataGridView DGV, out Decimal valTVA,Boolean cantitate=false)
        {
            
            Decimal total = Decimal.Zero;
            valTVA = Decimal.Zero;
            Decimal cant = Decimal.Zero;
            
            foreach (DataGridViewRow dr in DGV.Rows)
            {
                if (dr.Cells[CantitateColumn.Index].Value!=DBNull.Value)
                    cant = Convert.ToDecimal(dr.Cells[CantitateColumn.Index].Value);
                else
                    cant = Decimal.Zero;
                if (dr.Cells[indexColoana].Value != DBNull.Value)
                {
                    if(dr.Cells[indexColoana].IsInEditMode)
                        total += Convert.ToDecimal(dr.Cells[indexColoana].EditedFormattedValue) * (cantitate?cant:1);
                    else
                        total += Convert.ToDecimal(dr.Cells[indexColoana].Value) * (cantitate ? cant : 1);
                    
                }
                if (dr.Cells[idxColTVA].Value != DBNull.Value)
                {
                    if (dr.Cells[idxColTVA].IsInEditMode)
                    {
                        if (dr.Cells[idxColTVA].EditedFormattedValue.ToString().Trim() != String.Empty)
                            valTVA += Convert.ToDecimal(dr.Cells[idxColTVA].EditedFormattedValue);
                    }
                    else
                        valTVA += Convert.ToDecimal(dr.Cells[idxColTVA].Value);
                }
            }
            return total;
        }

        private void SetVisibility(Int16 IDTipDocument)
        {
            ///activ pentru facturi, aviz de expeditie, receptie
            listTSButton[IndexButonGF].Visible = IDTipDocument == 0 || IDTipDocument == 1 || IDTipDocument == 14 || IDTipDocument == 15;

            ////coloane tabel
            CantComandataColumn.Visible = ((IDTipDocument == 0) || (IDTipDocument == 15) || (IDTipDocument == 1) || (IDTipDocument == 13) || (IDTipDocument == 14));
            StocIntratColumn.Visible = ((IDTipDocument == 1) || (IDTipDocument == 13) || (IDTipDocument == 14)) && GestiuneaStocurilor && !FSRow.GestiuneCantitativa;
            StartProductieL.Visible = ((IDTipDocument == 9) || (IDTipDocument == 12)) && ProductieActivata;
            dataStartProductieDTP.Visible = ((IDTipDocument == 9) || (IDTipDocument == 12)) && ProductieActivata;
            TVAIncasareColumn.Visible = (IDTipDocument == 0 || IDTipDocument == 1) && FSRow.PermiteTVALaIncasare;
            TermenLivrareColumn.Visible = FSRow.FolosesteTermenLivrare && ((IDTipDocument == 9) || (IDTipDocument == 12));


            //fara data scadenta
            dataScadentaLabel.Visible = IDTipDocument == 0 || IDTipDocument == 1; dataScadentaDTP.Visible = dataScadentaLabel.Visible;
            ReceptieL.Visible = (IDTipDocument != 9) && (IDTipDocument != 12) && (IDTipDocument != 14) && (IDTipDocument != 13);
            nrDocReceptieTB.Visible = (IDTipDocument != 9) && (IDTipDocument != 12) && (IDTipDocument != 14) && (IDTipDocument != 13);
            dataDocReceptieDTP.Visible = (IDTipDocument != 9) && (IDTipDocument != 12) && (IDTipDocument != 14) && (IDTipDocument != 13);
        }

        private void documenteBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            if (documenteBindingSource.Current == null)
                return;
            DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                as DataSets.ESRPDataSet.DocumenteRow;
            if (PartenerCB.SelectedItem != null)
            {
                DataSets.ESRPDataSet.fares_ParteneriCUIRow pr = ((DataRowView)PartenerCB.SelectedItem).Row as DataSets.ESRPDataSet.fares_ParteneriCUIRow;
                String mesaj = String.Empty;
                if (!pr.IsContClientNull())
                    mesaj = "Cont client:" + pr.ContClient;
                mesaj += "\nCont furnizor: " + pr.Cont;
                toolTip1.SetToolTip(PartenerCB, mesaj);
            }

            splitContainerDocument.Enabled = rd.UserId == ModuleInfo.UserID;
            FrmMainMdi mm = (FrmMainMdi)MdiParent;
            eSRPDataSet.DocumenteDetaliu.IDRegimFiscalColumn.DefaultValue = rd.IDRegimFiscal;
            eSRPDataSet.DocumenteDetaliu.CotaTVAColumn.DefaultValue = rd.CotaTVA;
            mm.StergeTSB.Enabled = rd.UserId == ModuleInfo.UserID;
            /// se calculeaza totalul de pe document
            /// 
            if ((rd.IDTipDocument != 10) && (rd.IDTipDocument != 11) && (rd.TotalValoareTVA + rd.TotalValoare != rd.Total))
                rd.Total = rd.TotalValoareTVA + rd.TotalValoare;

            if (((rd.IDTipDocument == 10) || (rd.IDTipDocument == 11)) && (rd.Total != rd.TotalValoare))
                rd.Total = rd.TotalValoare;

            
            ValoareUnitaraValutaColumn.Visible = Valuta && (rd.CodValuta != MonedaImplicita);
            GestionarCB.Visible = (rd.IDTipDocument != 9) && (rd.IDTipDocument != 12) && FolosesteDepartamente && (rd.IDTipDocument != 14);
            GestionarL.Visible = (rd.IDTipDocument != 9) && (rd.IDTipDocument != 12) && FolosesteDepartamente && (rd.IDTipDocument != 14);

            ///seteaza eticheta de la receptie
            ///
            switch (rd.IDTipDocument)
            { 
                case 14:
                    ReceptieL.Text = "Comanda:";
                    break;
                case 15:
                    ReceptieL.Text = "Av. Exp.:";
                    break;
                default:
                    ReceptieL.Text = DocumenteIntrare ? "Receptie:" : "Av. Exp.:";
                    break;
            }
            
           



            //incarca dimensiunile din baza de date
            SqlConnection con = DeschideConexiune(workConnString);
            if (documentAnterior != null && documentAnterior.RowState!=DataRowState.Detached && documentAnterior.RowState!=DataRowState.Deleted)
            {
                SalveazaDimensiuni(con, documentAnterior.IDDocument, "Documente");
            }
            //SalveazaDimensiuni(con, rd.IDDocument, "Documente");
            LoadDimensiuni(con, rd.IDDocument, "Documente");
            documentAnterior = rd;
            InchideConexiune(con);
            tipDocumentCB.Enabled = ((DataRowView)documenteBindingSource.Current).IsNew && (FelDocument==-1);
            if (!((DataRowView)documenteBindingSource.Current).IsNew)
            {
                ValoareUnitaraValutaColumn.Visible = Valuta && (rd.CodValuta != MonedaImplicita);
                TotalValutaL.Visible = Valuta && (rd.CodValuta != MonedaImplicita);
                totalValutaNUD.Visible = Valuta && (rd.CodValuta != MonedaImplicita);
            }

            totalValoareTVATB.Visible = (rd.IDTipDocument != 9 && rd.IDTipDocument != 12);
            totalTB.Visible = (rd.IDTipDocument != 9 && rd.IDTipDocument != 12);
            totalValoareTVAL.Visible = (rd.IDTipDocument != 9 && rd.IDTipDocument != 12);
            totalLabel.Visible = (rd.IDTipDocument != 9 && rd.IDTipDocument != 12); 

            #region Comenzi fara pret

            cursValutarNUD.Visible = (Valuta && (rd.IDTipDocument != 9 && rd.IDTipDocument != 12)) ||
                ((rd.IDTipDocument == 9 || rd.IDTipDocument == 12) && !ComenziFaraPret && Valuta);
            leiL.Visible = (Valuta && (rd.IDTipDocument != 9 && rd.IDTipDocument != 12)) ||
                ((rd.IDTipDocument == 9 || rd.IDTipDocument == 12) && !ComenziFaraPret && Valuta);

            totalValoareTB.Visible = (rd.IDTipDocument != 9 && rd.IDTipDocument != 12) ||
                ((rd.IDTipDocument == 9 || rd.IDTipDocument == 12) && ((ComenziFaraPret && rd.CodValuta == MonedaImplicita) ||
                !ComenziFaraPret));
            totalValoareLabel.Visible = (rd.IDTipDocument != 9 && rd.IDTipDocument != 12) ||
                ((rd.IDTipDocument == 9 || rd.IDTipDocument == 12) && ((ComenziFaraPret && rd.CodValuta == MonedaImplicita) ||
                !ComenziFaraPret));

            ValoareUnitaraColumn.Visible = (rd.IDTipDocument != 9 && rd.IDTipDocument != 12) ||
                ((rd.IDTipDocument == 9 || rd.IDTipDocument == 12) && ((ComenziFaraPret && rd.CodValuta == MonedaImplicita) ||
                !ComenziFaraPret));

            ValoareTotalaColumn.Visible = (rd.IDTipDocument != 9 && rd.IDTipDocument != 12) ||
                ((rd.IDTipDocument == 9 || rd.IDTipDocument == 12) && ((ComenziFaraPret && rd.CodValuta == MonedaImplicita) ||
                !ComenziFaraPret));

            TotalValutaL.Visible = (rd.IDTipDocument != 9 && rd.IDTipDocument != 12 && Valuta && rd.CodValuta != MonedaImplicita) ||
                ((rd.IDTipDocument == 9 || rd.IDTipDocument == 12) && ((ComenziFaraPret && rd.CodValuta != MonedaImplicita) ||
                (!ComenziFaraPret && rd.CodValuta != MonedaImplicita)));

            totalValutaNUD.Visible = (rd.IDTipDocument != 9 && rd.IDTipDocument != 12 && Valuta && rd.CodValuta != MonedaImplicita) ||
                ((rd.IDTipDocument == 9 || rd.IDTipDocument == 12) && ((ComenziFaraPret && rd.CodValuta != MonedaImplicita) ||
                (!ComenziFaraPret && rd.CodValuta != MonedaImplicita)));

            if (ComenziFaraPret && (rd.IDTipDocument == 9 || rd.IDTipDocument == 12))
            {
                ObservatiiColumn.Width = 280;    
            }
            else
                ObservatiiColumn.Width = 100;    
            #endregion

            SetVisibility(rd.IDTipDocument);
        }

        private Decimal GestiuneaStocurilorProc(DataGridViewCellEventArgs e)
        {
            //can intra in campul de gestiune
            Decimal ret = -1;
            if (e!=null && e.ColumnIndex != CantitateColumn.Index)
                return ret;

            if (GestiuneaStocurilor)
            {
                if (documenteBindingSource.Current == null)
                    return ret;
                DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteRow;
                DataSets.ESRPDataSet.DocumenteDetaliuRow rdd = ((DataRowView)documenteDetaliuBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteDetaliuRow;

                if (((rd.IDTipDocument == 1 && ((e!=null && rd.AreDocGestStoc) || e==null)) || rd.IDTipDocument == 14))
                {
                    ShowWzdComenziStocuri(e.ColumnIndex, e.RowIndex, rdd, rd);

                }
                

            }
            return ret;
        }

        private void Copiaza(object sender, EventArgs e)
        {

            DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteRow;
            try
            {
                documenteBindingSource.AddNew();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
                return;
            }

            documenteBindingSource.MoveLast();
            DataSets.ESRPDataSet.DocumenteRow newrd = ((DataRowView)documenteBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteRow;
            newrd.IDPartener = rd.IDPartener;
            newrd.NrDoc = String.Empty;
            newrd.DataDoc = rd.DataDoc;
            newrd.IDRegimFiscal = rd.IDRegimFiscal;
            newrd.IDTipDocument = rd.IDTipDocument;
            if(!rd.IsIDDepartamentNull())
                newrd.IDDepartament = rd.IDDepartament;
            if (!rd.IsNrContractNull())
                newrd.NrContract = rd.NrContract;
            if (!rd.IsDataContractNull())
                newrd.DataContract = rd.DataContract;
            newrd.Total = rd.Total;
            newrd.TotalValoare = rd.TotalValoare;
            newrd.TotalValoareTVA = rd.TotalValoareTVA;
            newrd.UserId = ModuleInfo.UserID;
            documenteBindingSource.ResetCurrentItem();
            foreach (DataSets.ESRPDataSet.DocumenteDetaliuRow rdc in eSRPDataSet.DocumenteDetaliu.Select("IDDocument=" + rd.IDDocument.ToString()))
            {
                documenteDetaliuBindingSource.AddNew();
                //documenteDetaliuBindingSource.MoveLast();
                DataSets.ESRPDataSet.DocumenteDetaliuRow nrd = ((DataRowView)documenteDetaliuBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteDetaliuRow;
                nrd.IDArticol = rdc.IDArticol;
                nrd.IDDocument = newrd.IDDocument;
                nrd.IDRegimFiscal = rdc.IDRegimFiscal;
                nrd.IDUnitateMasura = rdc.IDUnitateMasura;
                nrd.ValoareTotala = rdc.ValoareTotala;
                nrd.ValoareTVA = rdc.ValoareTVA;
                nrd.ValoareUnitara = rdc.ValoareUnitara;
                nrd.Cantitate = rdc.Cantitate;
                nrd.CotaTVA = rdc.CotaTVA;
                if (!rdc.IsIDVariantaArticolNull())
                    nrd.IDVariantaArticol = rdc.IDVariantaArticol;
                

            }
            documenteDetaliuBindingSource.AddNew();
            documenteDetaliuBindingSource.RemoveCurrent();
            documenteDetaliuBindingSource.ResetCurrentItem();
            //documenteDetaliuBindingSource.MoveFirst();
            DocumenteFrm_HandleAfterAdd(this, null);
            Text = numeMacheta + " - Copie Document";

        }

        private void LoadVariante(Int32 idvariante)
        {
            articoleVarianteBindingSource.Filter = "IDArticol=" + idvariante;
            for (int i = 0; i < articoleVarianteBindingSource.Count; i++)
            { 
                DataSets.ESRPDataSet.ArticoleVarianteRow avr = ((DataRowView)articoleVarianteBindingSource.Current).Row as DataSets.ESRPDataSet.ArticoleVarianteRow;

                varianteArticoleSelectatBS.Add(new VarianteArticoleSelectat(avr.Denumire, avr.IDArticol, avr.PretVanzare));
                articoleVarianteBindingSource.MoveNext();
            }

        }

        private void denumireComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tipDocumentCB.SelectedItem == null || documenteBindingSource.Current == null)
                return;
            DataSets.ESRPDataSet.admin_DocumenteDisponibileRow ddr = ((DataRowView)tipDocumentCB.SelectedItem).Row as DataSets.ESRPDataSet.admin_DocumenteDisponibileRow;
            DataSets.ESRPDataSet.DocumenteRow docr = ((DataRowView)documenteBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteRow;

            //daca e comanda
            switch(ddr.IDTipDocument)
            {
                case 15:
                case 14: //AVIZ DE expeditie
                    // cu partener

                    PartenerCB.Visible = true; PartenerLabel.Visible = true;
                    GestionarL.Visible = ddr.IDTipDocument==15; GestionarCB.Visible = ddr.IDTipDocument==15;
                    if(ddr.IDTipDocument==15)
                        ReceptieL.Text = "Av. Exp.:";
                    if (ddr.IDTipDocument == 14)
                        ReceptieL.Text = "Comanda"; 
                    //fara TVA pe antet document
                    cotaTVANUD.Visible = false; cotaTVALabel.Visible = false;
                    
                    //fara regim fiscal
                    iDRegimFiscalCB.Visible = false; iDRegimFiscalL.Visible = false;
                    //predatorul este vizibil
                    PredatorCB.Visible = ddr.IDTipDocument==14; PredatorLabel.Visible = ddr.IDTipDocument==14;

                    ///detaliu in tabela
                    ///
                    CotaTVAColumn.Visible = false;
                    ValoareTVAColumn.Visible = false;
                    ValoareTotalaCuAdaosColumn.Visible = false;
                    regimFiscalColumn.Visible = false;
                    //totaluri la baza paginii

                    totalValoareTVAL.Visible = false; totalValoareTVATB.Visible = false;
                    totalTB.Visible = false; totalLabel.Visible = false;
                    
                    SerieNumerica = SeriiNumerice["AE"];
                    dataStartProductieDTP.Visible = false;
                    break;


                case 13: //bon de consum
                    // fara partener
                    PartenerCB.Visible = false; PartenerLabel.Visible=false;
                    ReceptieL.Text = "Comanda";
                    //fara TVA pe antet document
                    cotaTVANUD.Visible = false; cotaTVALabel.Visible = false;
                    //fara data scadenta
                    dataScadentaLabel.Visible = false; dataScadentaDTP.Visible = false;
                    //fara regim fiscal
                    iDRegimFiscalCB.Visible = false; iDRegimFiscalL.Visible=false;
                    //predatorul este vizibil
                    PredatorCB.Visible = true; PredatorLabel.Visible = true;
                    ///detaliu in tabela
                    ///
                    CotaTVAColumn.Visible = false;
                    ValoareTVAColumn.Visible = false;
                    ValoareTotalaCuAdaosColumn.Visible = false;
                    regimFiscalColumn.Visible = false;
                    //totaluri la baza paginii

                    totalValoareTVAL.Visible = false;totalValoareTVATB.Visible = false;
                    totalTB.Visible = false; totalLabel.Visible = false;
                    eSRPDataSet.Documente.IDPartenerColumn.DefaultValue = CodPartenerPentruBC;
                    ///nu e suficient valoare implicita daca s-a modificat tipu de document
                    docr.IDPartener = CodPartenerPentruBC;
                    SerieNumerica = SeriiNumerice["BC"];
                    dataStartProductieDTP.Visible = false;
                    break;

                case 9:
                case 12: //comanda
                    //predatorul este invizibil
                    PredatorCB.Visible = false; PredatorLabel.Visible = false;
                    PartenerCB.Visible = true; PartenerLabel.Visible=true;
                    totalValoareTVATB.Visible = false;
                    totalValoareTVAL.Visible = false;
                    ValoareTVAColumn.Visible = false;
                    cotaTVANUD.Visible = false;
                    eSRPDataSet.DocumenteDetaliu.ValoareTVAColumn.DefaultValue = 0; //fara regim fiscal
                    eSRPDataSet.DocumenteDetaliu.IDRegimFiscalColumn.DefaultValue = 0;
                    cotaTVALabel.Visible = false;
                    iDRegimFiscalCB.Visible = false;
                    iDRegimFiscalL.Visible = false;
                    regimFiscalColumn.Visible = false;
                    CotaTVAColumn.Visible = false;
                    ValoareTVAColumn.Visible = false;
                    ValoareUnitaraColumn.Visible =((ComenziFaraPret && docr.CodValuta == MonedaImplicita) || !ComenziFaraPret);
                    ValoareTotalaCuAdaosColumn.Visible = DocumenteIntrare && FolosesteValoareTotalaCuAdaos;
                    regimFiscalColumn.Visible = RegimFiscalDetaliu;
                    totalTB.Visible = true; totalLabel.Visible = true;

                    eSRPDataSet.Documente.IDPartenerColumn.DefaultValue = null;
                    SerieNumerica = SeriiNumerice["DOC"];
                    break;

                case 10:
                case 11: //bon fiscal
                    //predatorul este invizibil
                    PredatorCB.Visible = false; PredatorLabel.Visible = false;
                    PartenerCB.Visible = true; PartenerLabel.Visible=true;
                    CotaTVAColumn.Visible = CotaTVAActivaDetaliu;
                    ValoareTVAColumn.Visible = true;
                    ValoareTotalaCuAdaosColumn.Visible = DocumenteIntrare && FolosesteValoareTotalaCuAdaos;
                    regimFiscalColumn.Visible = RegimFiscalDetaliu;
                    //totaluri la baza machetei
                    totalValoareTVATB.Visible = true; totalValoareTVAL.Visible = true;
                    totalTB.Visible = true; totalLabel.Visible = true;
                    eSRPDataSet.Documente.IDPartenerColumn.DefaultValue = null;
                    SerieNumerica = SeriiNumerice["BF"];
                    break;
                default:
                    //factura
                    PartenerCB.Visible = true; PartenerLabel.Visible=true;
                    //predatorul este invizibil
                    
                    PredatorCB.Visible = !DocumenteIntrare; PredatorLabel.Visible = !DocumenteIntrare;
                    GestionarL.Visible = DocumenteIntrare; GestionarCB.Visible = DocumenteIntrare;

                    ValoareUnitaraColumn.Visible = true;
                    totalValoareTVATB.Visible = true; totalValoareTVAL.Visible = true;
                    
                    ValoareTVAColumn.Visible = true;
                    eSRPDataSet.DocumenteDetaliu.ValoareTVAColumn.DefaultValue = DBNull.Value;
                    //eSRPDataSet.DocumenteDetaliu.IDRegimFiscalColumn.DefaultValue = docr.IDRegimFiscal;
                    cotaTVANUD.Visible = true;
                    cotaTVALabel.Visible = true;
                    iDRegimFiscalCB.Visible = true;
                    iDRegimFiscalL.Visible = true;
                    regimFiscalColumn.Visible = RegimFiscalDetaliu;
                    CotaTVAColumn.Visible = CotaTVAActivaDetaliu;
                    this.ValoareTotalaColumn.ReadOnly = true;
                    ValoareTotalaCuAdaosColumn.Visible = DocumenteIntrare && FolosesteValoareTotalaCuAdaos;
                    totalTB.Visible = true; totalLabel.Visible = true;
                    eSRPDataSet.Documente.IDPartenerColumn.DefaultValue = null;
                    SerieNumerica = SeriiNumerice["DOC"];
                    break;
            }
            ValoareTotalaColumn.Visible = (ddr.IDTipDocument != 9 && ddr.IDTipDocument != 12) ||
                ((ddr.IDTipDocument == 9 || ddr.IDTipDocument == 12) && ((ComenziFaraPret && docr.CodValuta == MonedaImplicita) ||
                !ComenziFaraPret));

            ValoareUnitaraValutaColumn.Visible = Valuta && (docr.CodValuta != MonedaImplicita);


            if (!((DataRowView)documenteBindingSource.Current).IsNew)
                return;


            
            SqlConnection conn = DeschideConexiune(workConnString);
            SetNextSerialNumber(conn);
            SetSetariLocale(conn, DocumenteIntrare?"DDIC":"DDOC", ddr.IDTipDocument.ToString(), ModuleInfo.CodUnitate);
            eSRPDataSet.Documente.IDTipDocumentColumn.DefaultValue = ddr.IDTipDocument;
            InchideConexiune(conn);
            SetVisibility(ddr.IDTipDocument);
            
        }
          
        private Decimal _initialTVA = Decimal.Zero;
        private void cotaTVANUD_Enter(object sender, EventArgs e)
        {
            _initialTVA = ((NumericUpDown)sender).Value;
        }

        private void cotaTVANUD_ValueChanged(object sender, EventArgs e)
        {
        }

        private Boolean CalculeazaTVALinie(int RowIndex,Decimal val,Int16 idRegim,Int32 tipDocument)
        {
            Boolean modificat = false;
            Decimal tva = Decimal.Zero;
            if(docDetaliuDGV[CotaTVAColumn.Index, RowIndex].Value != DBNull.Value)
                tva=Convert.ToDecimal(docDetaliuDGV[CotaTVAColumn.Index, RowIndex].Value != DBNull.Value);
            if ((RegimuriTVANeZero.Contains(idRegim)) || !RegimuriTVAZero.Contains(idRegim))
            {
                Decimal tvaProc = Decimal.Zero;
                if (tipDocument == 10 || tipDocument == 11)
                {
                    if (docDetaliuDGV[CotaTVAColumn.Index, RowIndex].IsInEditMode)
                        tvaProc = Convert.ToDecimal(docDetaliuDGV[CotaTVAColumn.Index, RowIndex].EditedFormattedValue);
                    else
                        tvaProc = Convert.ToDecimal(docDetaliuDGV[CotaTVAColumn.Index, RowIndex].Value);
                    Decimal tvaVal =Decimal.Round(val - (val * (Decimal)100.00 / ((Decimal)100.00 + tvaProc)),2);
                    if ((docDetaliuDGV[ValoareTVAColumn.Index, RowIndex].Value == DBNull.Value) || (Convert.ToDecimal(docDetaliuDGV[ValoareTVAColumn.Index, RowIndex].Value) != tvaVal))
                    {
                        docDetaliuDGV[ValoareTVAColumn.Index, RowIndex].Value = tvaVal;
                        modificat = true;
                    }
                }
                else
                {
                    if (docDetaliuDGV[CotaTVAColumn.Index, RowIndex].IsInEditMode)
                        tvaProc = Convert.ToDecimal(docDetaliuDGV[CotaTVAColumn.Index, RowIndex].EditedFormattedValue);
                    else
                        tvaProc = Convert.ToDecimal(docDetaliuDGV[CotaTVAColumn.Index, RowIndex].Value);
                    Decimal tvaVal = Decimal.Round((val * tvaProc) / ((Decimal)100.00),2);
                    if ((docDetaliuDGV[ValoareTVAColumn.Index, RowIndex].Value == DBNull.Value) || (Convert.ToDecimal(docDetaliuDGV[ValoareTVAColumn.Index, RowIndex].Value) != tvaVal))
                    {
                        docDetaliuDGV[ValoareTVAColumn.Index, RowIndex].Value = tvaVal;
                        modificat = true;
                    }
                }

            }
            else
            if (RegimuriTVAZero.Contains(idRegim))
            {
                
                Decimal tvaVal = Decimal.Zero;
                if ((docDetaliuDGV[ValoareTVAColumn.Index, RowIndex].Value == DBNull.Value) || (Convert.ToDecimal(docDetaliuDGV[ValoareTVAColumn.Index, RowIndex].Value) != tvaVal))
                {
                    docDetaliuDGV[ValoareTVAColumn.Index, RowIndex].Value = tvaVal;
                    docDetaliuDGV[CotaTVAColumn.Index, RowIndex].Value = Decimal.Zero;
                    modificat = true;
                }
            }

            return modificat;
        }

        private Boolean CalculeazaTVALinieBindingSource(ref DataSets.ESRPDataSet.DocumenteDetaliuRow ddr, Decimal val, Int16 idRegim, Int32 tipDocument)
        {
            Boolean modificat = false;
            //Decimal tva = Decimal.Zero;
            //if (docDetaliuDGV[CotaTVAColumn.Index, RowIndex].Value != DBNull.Value)
            //    tva = Convert.ToDecimal(docDetaliuDGV[CotaTVAColumn.Index, RowIndex].Value != DBNull.Value);


            if ((RegimuriTVANeZero.Contains(idRegim)) || !RegimuriTVAZero.Contains(idRegim))
            {
                Decimal tvaProc = Decimal.Zero;
                if (tipDocument == 10 || tipDocument == 11)
                {
                    tvaProc = ddr.CotaTVA;
                    Decimal tvaVal = Decimal.Round(val - (val * (Decimal)100.00 / ((Decimal)100.00 + tvaProc)), 2);
                    ddr.ValoareTVA = tvaVal;
                    modificat = true;
                }
                else
                {
                    tvaProc = ddr.CotaTVA;
                    Decimal tvaVal = Decimal.Round((val * tvaProc) / ((Decimal)100.00), 2);
                    ddr.ValoareTVA = tvaVal;
                    modificat = true;
                }

            }
            else
                if (RegimuriTVAZero.Contains(idRegim))
                {
                    Decimal tvaVal = Decimal.Zero;
                    ddr.ValoareTVA = tvaVal;
                    ddr.CotaTVA = Decimal.Zero;
                    modificat = true;
                }

            return modificat;
        }

        #region Functii dimensiuni
        private void CreazaDimensiuni(SqlConnection con)
        {
            SqlCommand comand = new SqlCommand("SELECT * FROM TipDimensiune WHERE Vizibila=1", con);
            SqlDataReader
                dr = comand.ExecuteReader();
            int rand = 0;
            while (dr.Read())
            {
                if (dr["Format"].ToString() == "SL")
                {
                    listDimLabel.Add(new Label());
                    int idx = listDimLabel.Count - 1;
                    listDimLabel[idx].Location = new Point(splitContainerDocument.Panel1.Width - 220, rand * 21 + 16);
                    listDimLabel[idx].Text = dr["Denumire"].ToString();
                    listDimLabel[idx].Visible = true;
                    listDimLabel[idx].Name = dr["Denumire"].ToString() + "L";
                    listDimLabel[idx].Parent = splitContainerDocument.Panel1;
                    listDimLabel[idx].AutoEllipsis = true;
                    listDimLabel[idx].AutoSize = false;
                    listDimLabel[idx].Width = 80;


                    listDimCombo.Add(new ComboBox());
                    idx = listDimLabel.Count - 1;
                    listDimCombo[idx].Location = new Point(splitContainerDocument.Panel1.Width - 140, rand * 21 + 12);
                    //listDimCombo[idx].Text = dr["Denumire"].ToString();
                    listDimCombo[idx].Visible = true;
                    listDimCombo[idx].Name = dr["Denumire"].ToString() + "CB";
                    listDimCombo[idx].Parent = splitContainerDocument.Panel1;
                    listDimCombo[idx].Tag = new InfoDimensiune("", Convert.ToInt16(dr["IDTipDimensiune"]));

                }
                rand++;
            }
            dr.Close();
        }

        private void LoadDimensiuni(SqlConnection con, Int64 cheie, String tabela)
        {
            SqlCommand comand = new SqlCommand("SELECT a.*,b.Format FROM ValoriDimensiuni a JOIN TipDimensiune b ON a.IDTipDimensiune=b.IDTipDimensiune WHERE b.Vizibila=1 AND Tabela='" + tabela + "' AND [IDCheieTabela]=" + cheie.ToString() +
                " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString(), con);
            SqlDataReader
                dr = comand.ExecuteReader();

            ///le initializeaza
            ///
            foreach (ComboBox cb in listDimCombo)
                if (cb.Tag != null)
                {
                    ((InfoDimensiune)cb.Tag).valoareInitiala = String.Empty;
                    ((InfoDimensiune)cb.Tag).areDBRec = false;
                    cb.Text = String.Empty;
                }

            while (dr.Read())
            {
                if (dr["Format"].ToString() == "SL")
                {
                    foreach (ComboBox cb in listDimCombo)
                    {
                        if (((InfoDimensiune)cb.Tag).idTipDimensiune == Convert.ToInt16(dr["IDTipDimensiune"]))
                        {
                            cb.Text = dr["Valoare"].ToString();
                            ((InfoDimensiune)cb.Tag).valoareInitiala = cb.Text;
                            // adica are inregistrare in baza de date
                            ((InfoDimensiune)cb.Tag).areDBRec = true;
                        }
                    }
                }
            }
            dr.Close();
        }

        private void SalveazaDimensiuni(SqlConnection con, Int64 cheie, String Tabela)
        {
            SqlCommand comand = new SqlCommand("", con);
            foreach (ComboBox cb in listDimCombo)
            {
                if (cb.Text != ((InfoDimensiune)cb.Tag).valoareInitiala)
                {
                    if (cb.Text != String.Empty)
                    {
                        if (((InfoDimensiune)cb.Tag).areDBRec)
                            comand.CommandText = "UPDATE [ValoriDimensiuni] SET [Valoare]='" + cb.Text + "' WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND [IDCheieTabela]=" +
                                cheie.ToString() + " AND [IDTipDimensiune]=" + ((InfoDimensiune)cb.Tag).idTipDimensiune.ToString();
                        else
                        {
                            comand.CommandText = "INSERT INTO [ValoriDimensiuni]([IDTipDimensiune],[Tabela],[IDCheieTabela],[Valoare],[CodUnitate]) VALUES (" +
                                ((InfoDimensiune)cb.Tag).idTipDimensiune.ToString() + ",'" + Tabela + "'," + cheie.ToString() + ",'" + cb.Text + "'," + ModuleInfo.CodUnitate.ToString() + ")";
                            ((InfoDimensiune)cb.Tag).areDBRec = true;
                        }
                    }
                    else
                    {
                        if (((InfoDimensiune)cb.Tag).areDBRec)
                        {
                            comand.CommandText = "DELETE FROM [ValoriDimensiuni]  WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND [IDCheieTabela]=" +
                                cheie.ToString() + " AND [IDTipDimensiune]=" + ((InfoDimensiune)cb.Tag).idTipDimensiune.ToString();
                            ((InfoDimensiune)cb.Tag).areDBRec = false;
                        }

                    }
                    comand.ExecuteNonQuery();
                }
            }
        }
        
        #endregion

       
        private void iDRegimFiscalCB_Leave(object sender, EventArgs e)
        {
           
        }


        private void cotaTVANUD_Leave(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dr in docDetaliuDGV.Rows)
            {
                if (Convert.ToDecimal(dr.Cells[CotaTVAColumn.Index].Value) == _initialTVA && !dr.IsNewRow)
                {
                    dr.Cells[CotaTVAColumn.Index].Value = cotaTVANUD.Value;
                    Decimal vn = Decimal.Zero;
                    if (dr.Cells[ValoareTotalaColumn.Index].Value != DBNull.Value && dr.Cells[CotaTVAColumn.Index].Value != DBNull.Value)
                        vn = Convert.ToDecimal(dr.Cells[ValoareTotalaColumn.Index].Value) * Convert.ToDecimal(dr.Cells[CotaTVAColumn.Index].Value) / 100;
                    if (dr.Cells[ValoareTVAColumn.Index].Value == DBNull.Value || Convert.ToDecimal(dr.Cells[ValoareTVAColumn.Index].Value) != vn)
                        dr.Cells[ValoareTVAColumn.Index].Value = vn;
                }
            }
            if (documenteBindingSource.Current != null)
            {
                DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                    as DataSets.ESRPDataSet.DocumenteRow;
                SeteazaTotalDocument(rd.IDTipDocument);
            }

            _initialTVA = cotaTVANUD.Value;
            eSRPDataSet.DocumenteDetaliu.CotaTVAColumn.DefaultValue = cotaTVANUD.Value;

        }

        private void NrDocTB_Leave(object sender, EventArgs e)
        {
            if (documenteBindingSource.Current == null)
                return;
            DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                as DataSets.ESRPDataSet.DocumenteRow;

            SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM [Documente] a JOIN [TipDocument] td ON td.IDTipDocument=a.IDTipDocument WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() +
                " AND td.TipOperatie LIKE '%" + (DocumenteIntrare ? "I" : "O") + "%' AND NrDoc='"+ NrDocTB.Text.Trim() + "' AND [IDDocument]<>"+rd.IDDocument, DeschideConexiune(workConnString));
            Int32 cate = Convert.ToInt32(cmd.ExecuteScalar());
            InchideConexiune(cmd.Connection);

            if (cate > 0 )
                beepTime();

        }

        private void DeleteError_Enter(object sender, EventArgs e)
        {
            errorProvider1.SetError((Control)sender, String.Empty);
        }

        //private void departamentCB_Validated(object sender, EventArgs e)
        //{
        //    String denControl = ((ComboBox)sender).Text.Trim(), idRecSel = String.Empty;
        //    String idGestionarImplicit = String.Empty;
        //    if (denControl == String.Empty)
        //        return;
        //    searchDepartamentBS.RemoveFilter();
        //    searchDepartamentBS.Filter = "Nume like '%" + denControl + "%' AND CodUnitate=" + ModuleInfo.CodUnitate.ToString();
        //    int nrRecFound = searchDepartamentBS.Count;

        //    FrmMainMdi frm = this.MdiParent as FrmMainMdi;
        //    Assembly asm = frm.GetModule("erpforms");
        //    if (asm == null)
        //        return;

        //    if (nrRecFound == 0)
        //    {
        //        String numeClasa = "ERPForms.DepartamenteFrm";
        //        Type mModule = asm.GetType(numeClasa);

        //        if (mModule != null)
        //        {
        //            FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
        //                new object[] { ModuleInfo}, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;
        //            mModule.InvokeMember("DenumireDepartament", BindingFlags.SetProperty, null, newFrm, new object[] { denControl });
        //            newFrm.SelectionAddOn = true;
        //            newFrm.ShowDialog();
        //            denControl = newFrm.currentRow.Row["Nume"].ToString().ToUpper();
        //            idRecSel = newFrm.currentRow.Row["IDDepartament"].ToString();
        //            idGestionarImplicit = newFrm.currentRow.Row["IDGestionar"].ToString();  
        //            //incarca lista deparamentelor

        //            departamenteTableAdapter.Connection = DeschideConexiune(workConnString);
        //            departamenteTableAdapter.Fill(eSRPDataSet.Departamente);

        //            gestionariTableAdapter.Connection = departamenteTableAdapter.Connection;
        //            gestionariTableAdapter.Fill(eSRPDataSet.Gestionari);
        //            InchideConexiune(departamenteTableAdapter.Connection);

        //            ((ComboBox)sender).Text = denControl; 
        //        }
        //    }
        //    else
        //    {
        //        //if (nrRecFound > 1)
        //        //{
        //        //    String numeClasa = "ERPForms.DepartamenteFrm";
        //        //    Type mModule = asm.GetType(numeClasa);

        //        //    if (mModule != null)
        //        //    {
        //        //        FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
        //        //            new object[] { ModuleInfo}, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;

        //        //        //mModule.InvokeMember("DenumirePartener", BindingFlags.SetProperty, null, newFrm, new object[] { denControl });
        //        //        newFrm.SelectionAddOn = true;

        //        //        if (newFrm.ShowDialog() == DialogResult.OK)
        //        //        {
        //        //            idRecSel = newFrm.currentRow.Row["IDDepartament"].ToString();
        //        //            idGestionarImplicit = newFrm.currentRow.Row["IDGestionar"].ToString();  

        //        //            /// incarca actualizarile
        //        //            departamenteTableAdapter.Connection = DeschideConexiune(workConnString);
        //        //            departamenteTableAdapter.Fill(eSRPDataSet.Departamente);

        //        //            gestionariTableAdapter.Connection = departamenteTableAdapter.Connection;
        //        //            gestionariTableAdapter.Fill(eSRPDataSet.Gestionari);
        //        //            InchideConexiune(departamenteTableAdapter.Connection);

        //        //        }
        //        //        else
        //        //        {
        //        //            PartenerCB.Text = String.Empty;
        //        //            idRecSel = String.Empty;
        //        //            idGestionarImplicit = String.Empty;
        //        //        }
        //        //        newFrm.Close();
        //        //        if (newFrm != null)
        //        //            newFrm.Dispose();
        //        //    }
        //        //}
        //        //else
        //        {
        //            DataSets.ESRPDataSet.DepartamenteRow partr = ((DataRowView)searchDepartamentBS.Current).Row as DataSets.ESRPDataSet.DepartamenteRow;
        //                //daca s-a selectat alt departament
        //            idRecSel = partr.IDDepartament.ToString();
        //            if (!partr.IsIDGestionarNull())
        //                idGestionarImplicit = partr.IDGestionar.ToString();
        //        }
        //    }

        //    //if (documenteBindingSource.Current == null)
        //    //    return;
        //    //DataSets.ESRPDataSet.DocumenteRow docr = ((DataRowView)documenteBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteRow;

        //    //if (idRecSel != String.Empty && (docr.IsIDDepartamentNull() || docr.IDDepartament != Convert.ToInt32(idRecSel)))
        //    //{
        //    //    departamenteBindingSource.Sort = "IDDepartament";
        //    //    departamenteBindingSource.Position = departamenteBindingSource.Find("IDDepartament", Convert.ToInt32(idRecSel));

        //    //    if (idGestionarImplicit != String.Empty && docr.IsIDGestionarNull())
        //    //    {
        //    //        gestionariBindingSource.Sort = "IDGestionar";
        //    //        gestionariBindingSource.Position = gestionariBindingSource.Find("IDGestionar", Convert.ToInt32(idGestionarImplicit));
        //    //    }
        //    //}

        //}

        private void GestionarCB_Validated(object sender, EventArgs e)
        {
            String denControl = ((ComboBox)sender).Text.Trim(), idRecSel = String.Empty;
            if (denControl == String.Empty)
                return;
            searchGestionarBS.RemoveFilter();
            searchGestionarBS.Filter = "NumePrenume like '%" + denControl + "%'";
            int nrRecFound = searchGestionarBS.Count;

            FrmMainMdi frm = this.MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("erpforms");
            if (asm == null)
                return;

            if (nrRecFound == 0)
            {
                String numeClasa = "ERPForms.GestionariFrm";
                Type mModule = asm.GetType(numeClasa);

                if (mModule != null)
                {
                    FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                        new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;
                    mModule.InvokeMember("Denumire", BindingFlags.SetProperty, null, newFrm, new object[] { denControl });
                    newFrm.SelectionAddOn = true;
                    newFrm.ShowDialog();

                    denControl = newFrm.currentRow.Row["NumePrenume"].ToString().ToUpper();
                    idRecSel = newFrm.currentRow.Row["IDGestionar"].ToString();
                    //incarca lista deparamentelor

                    gestionariTableAdapter.Connection = DeschideConexiune(workConnString);
                    gestionariTableAdapter.Fill(eSRPDataSet.Gestionari);
                    InchideConexiune(departamenteTableAdapter.Connection);

                    ((ComboBox)sender).Text = denControl;
                }
            }
            else
            {
                if (nrRecFound > 1)
                {
                    String numeClasa = "ERPForms.GestionariFrm";
                    Type mModule = asm.GetType(numeClasa);

                    if (mModule != null)
                    {
                        FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                            new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;

                        //mModule.InvokeMember("DenumirePartener", BindingFlags.SetProperty, null, newFrm, new object[] { denControl });
                        newFrm.SelectionAddOn = true;

                        if (newFrm.ShowDialog() == DialogResult.OK)
                        {
                            idRecSel = newFrm.currentRow.Row["IDGestionar"].ToString();
                            /// incarca actualizarile
                            gestionariTableAdapter.Connection = DeschideConexiune(workConnString);
                            gestionariTableAdapter.Fill(eSRPDataSet.Gestionari);
                            InchideConexiune(departamenteTableAdapter.Connection);

                        }
                        else
                        {
                            idRecSel = String.Empty;
                        }
                        newFrm.Close();
                        if (newFrm != null)
                            newFrm.Dispose();
                    }
                }
                /*else
                {
                    DataSets.ESRPDataSet.DepartamenteRow partr = ((DataRowView)searchDepartamentBS.Current).Row as DataSets.ESRPDataSet.DepartamenteRow;
                    //daca s-a selectat alt departament
                    idRecSel = partr.IDDepartament.ToString();
                }*/
            }


            if (idRecSel != String.Empty)
            {
                gestionariBindingSource.Sort = "IDGestionar";
                gestionariBindingSource.Position = gestionariBindingSource.Find("IDGestionar", Convert.ToInt32(idRecSel));
            }
        }

        private void docDetaliuDGV_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            
            SelecteazaPretulVanzarePartener(e.RowIndex,e.ColumnIndex);
        }

        private void dataDocDTP_Validating(object sender, CancelEventArgs e)
        {
            codValutaCB_Validated(sender, e);
        }

        private void faresParteneriCUIBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            if (faresParteneriCUIBindingSource.Current != null)
            {
                DataSets.ESRPDataSet.fares_ParteneriCUIRow pr = ((DataRowView)faresParteneriCUIBindingSource.Current).Row as DataSets.ESRPDataSet.fares_ParteneriCUIRow;
                ConditiiPB.Visible = !pr.IsConditiiDePlataNull() && pr.ConditiiDePlata != String.Empty;
                if (!pr.IsConditiiDePlataNull())
                    toolTip1.SetToolTip(ConditiiPB, pr.ConditiiDePlata);
            }
            else
            {
                ConditiiPB.Visible = false;
                toolTip1.SetToolTip(ConditiiPB, String.Empty);
            }

        }

        private void codValutaCB_Validated(object sender, EventArgs e)
        {
            DataRowView drv = (DataRowView)documenteBindingSource.Current;
            if (codValutaCB.SelectedItem == null || drv == null)
                return;

            DataSets.ESRPDataSet.DocumenteRow dr = drv.Row as DataSets.ESRPDataSet.DocumenteRow;
            DataSets.ESRPDataSet.ValutaRow vr = ((DataRowView)codValutaCB.SelectedItem).Row as DataSets.ESRPDataSet.ValutaRow;
            if (vr.MonedaImplicita)
            {
                ValoareUnitaraValutaColumn.Visible = false;
                ValoareUnitaraColumn.Visible = true;
                TotalValutaL.Visible = false;
                totalValutaNUD.Visible = false;
                totalValoareTB.Visible = true;
                totalValoareLabel.Visible = true;

                return;
            }
            ///daca nu e moneda implicita cauta cursul
            ///
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
            cmd.CommandText = "SELECT ValoareLei FROM [ValutaCurs] WHERE CodValuta=" + vr.CodValuta.ToString() + " AND [IDBanca]=" + BancaImplicita.ToString() + " AND Data='" +
                dr.DataDoc.Year.ToString() + "-" + dr.DataDoc.Month.ToString() + "-" + dr.DataDoc.Day.ToString() + "'";
            Object ret = cmd.ExecuteScalar();
            ///daca este un document nou

            if ((dr.IDTipDocument != 9 && dr.IDTipDocument != 12) || ((dr.IDTipDocument == 9 || dr.IDTipDocument == 12) && !ComenziFaraPret))
            {
                while (ret == null || ret == DBNull.Value)
                {
                    FrmMainMdi frm = this.MdiParent as FrmMainMdi;
                    Assembly asm = frm.GetModule("erpforms");
                    String numeClasa = "ERPForms.CursValutarFrm";
                    Type mModule = asm.GetType(numeClasa);

                    if (mModule != null)
                    {
                        FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                            new object[] { ModuleInfo, vr.CodValuta, BancaImplicita, dr.DataDoc }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;
                        newFrm.ShowDialog();
                        ret = cmd.ExecuteScalar();
                    }
                }
                cursValutarNUD.Value = Convert.ToDecimal(ret);
                dr.CursValutar = cursValutarNUD.Value;
            }

            ValoareUnitaraValutaColumn.Visible = true;
            ValoareTotalaColumn.Visible = (dr.IDTipDocument != 9 && dr.IDTipDocument != 12) ||
               ((dr.IDTipDocument == 9 || dr.IDTipDocument == 12) && ((ComenziFaraPret && dr.CodValuta == MonedaImplicita) ||
               !ComenziFaraPret));
            ValoareUnitaraColumn.Visible = (dr.IDTipDocument != 9 && dr.IDTipDocument != 12);
            TotalValutaL.Visible = true;
            totalValutaNUD.Visible = true;
            totalValoareTB.Visible = false;
            totalValoareLabel.Visible = false;

        }

        private void cursValutarNUD_Validated(object sender, EventArgs e)
        {
            DataRowView drv = (DataRowView)documenteBindingSource.Current;
            if (codValutaCB.SelectedItem == null || drv == null)
                return;

            DataSets.ESRPDataSet.DocumenteRow dr = drv.Row as DataSets.ESRPDataSet.DocumenteRow;
            dr.CursValutar = cursValutarNUD.Value;
            Int32 tipDoc = 0;
            if (tipDocumentCB.SelectedValue != null)
                tipDoc = Convert.ToInt32(tipDocumentCB.SelectedValue);
            foreach (DataGridViewRow drr in docDetaliuDGV.Rows)
            {
                if(!drr.IsNewRow)
                    ActualizeazaValoareaTotalaLinie(Decimal.Zero, tipDoc, drr.Index, Convert.ToDecimal(drr.Cells[ValoareUnitaraValutaColumn.Index].Value));
            }
        }

        private void IncasarePlata(object sender, EventArgs e)
        {
            if (documenteBindingSource.Current == null)
                return;
            Salvare();
            PlatiFrm frm = null;
            DataSets.ESRPDataSet.DocumenteRow dr = ((DataRowView)documenteBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteRow;
            if (dr.IDTipDocument == 1 || dr.IDTipDocument == 0)
            {
                //daca este factura fiscala
                frm = new PlatiFrm(ModuleInfo, true, dr.IDPartener, dr.DataDoc, dr.TotalValoareTVA + dr.TotalValoare, dr.TotalValoareTVA, dr.IDDocument,dr.IDTipDocument == 1?"O":"I");
            }
            if(frm!=null)
                frm.ShowDialog();
        }


        private void GenereazaFactura(object sender, EventArgs e)
        {
            if (documenteBindingSource.Current == null)
                return;
            DataSets.ESRPDataSet.DocumenteRow dr = ((DataRowView)documenteBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteRow;
            /// nu a fost selectat nici un partener atunci da un mesaj
            /// 

            if (PartenerCB.SelectedIndex == -1)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare", "Vă rugăm să selectaţi PARTENERUL înainte de a genera liniile documentului!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, dr);
                mbt.AddButton("Iesire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                PartenerCB.Focus();
                return;            
            }

            ComenziWizFrm frm = new ComenziWizFrm(ModuleInfo, -1, -1, Convert.ToInt64(PartenerCB.SelectedValue),dr.IDTipDocument);
            frm.WizardComenzi = true;
            if (frm.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;
            //parcurge randurile selectate din grid
            foreach (DataGridViewRow dgvr in frm.comenziDGV.Rows)
            {
                /// Se adauga randul nou selecta la comanda
                if (Convert.ToBoolean(dgvr.Cells[frm.IndexSelect].Value) == true)
                {
                    //trebuie adaugat
                    DataRowView ddAdd = documenteDetaliuBindingSource.AddNew() as DataRowView;
                    DataSets.ESRPDataSet.DocumenteDetaliuRow ddr = ddAdd.Row as DataSets.ESRPDataSet.DocumenteDetaliuRow;
                    if (ddr != null)
                    { 
                        ddr.IDArticol = Convert.ToInt32(dgvr.Cells[frm.IndexIDArticol].Value);
                        ddr.IDUnitateMasura = Convert.ToInt16(dgvr.Cells[frm.IndexUM].Value);
                        ddr.Cantitate = Convert.ToInt32(dgvr.Cells[frm.IndexCantitate].Value);
                        ddr.ValoareUnitara = Convert.ToDecimal(dgvr.Cells[frm.IndexValoareLei].Value);
                        ddr.ValoareUnitaraValuta = Convert.ToDecimal(dgvr.Cells[frm.IndexValoareValuta].Value);
                        ddr.IDRegimFiscal = dr.IDRegimFiscal;
                        ddr.EndEdit();
                        ActualizeazaValoareaTotalaLinieBindingSource(ddr.ValoareUnitara, dr.IDTipDocument, ref ddr);

                        DataRowView ret = LinkBindingSource.AddNew() as DataRowView;
                        DataSets.ESRPDataSet.DocumenteDetaliuLinkRow ddrl = ret.Row as DataSets.ESRPDataSet.DocumenteDetaliuLinkRow;
                        if (ddrl != null)
                        {
                            ddrl.IDDocDetaliuDest = ddr.IDDocumentDetaliu;
                            ddrl.IDDocDetaliuSursa = Convert.ToInt32(dgvr.Cells[frm.IndexIDDocDetaliuSursa].Value);
                            ddrl.EndEdit();
                        }
                    }
                }
                LinkBindingSource.EndEdit();
                documenteDetaliuBindingSource.EndEdit();

            }

        } 

        private Decimal SelecteazaPretulVanzarePartener(int RowIndex,int ColumnIndex)
        {
            Decimal ret = decimal.Zero;
            if (ColumnIndex == ValoareUnitaraColumn.Index || ColumnIndex == ValoareUnitaraValutaColumn.Index)
            {
                if (documenteBindingSource.Current == null)
                    return Decimal.Zero;
                if(documenteDetaliuBindingSource.Current==null)
                    return Decimal.Zero;
                if (Convert.ToDecimal(docDetaliuDGV[ColumnIndex, RowIndex].EditedFormattedValue) != 0)
                    return Decimal.Zero;
                DataSets.ESRPDataSet.DocumenteRow dr = ((DataRowView)documenteBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteRow;
                DataSets.ESRPDataSet.DocumenteDetaliuRow ddr = ((DataRowView)documenteDetaliuBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteDetaliuRow;
                if (dr.IDTipDocument == 12) //comanda de vanzare
                {
                    Int32 idArt = -1;
                    articolePreturiBindingSource.Filter = "IDPartener=" + dr.IDPartener.ToString();
                    if(ddr.IDArticol!=null)
                        idArt = ddr.IDArticol;
                    if (articolePreturiBindingSource.Count != 0)
                    {
                        ArticolePreturiFrm frm = new ArticolePreturiFrm(ModuleInfo,idArt,dr.IDPartener,dr.CodValuta);
                        frm.SelectionAddOn = true;
                        if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            if (docDetaliuDGV[ColumnIndex, RowIndex].IsInEditMode)
                                docDetaliuDGV.EditingControl.Text = frm.selectedRow.Cells["pretVanzareColumn"].Value.ToString();
                            else
                                docDetaliuDGV[ColumnIndex, RowIndex].Value = frm.selectedRow.Cells["pretVanzareColumn"].Value;
                            ret = Convert.ToDecimal(frm.selectedRow.Cells["pretVanzareColumn"].Value);
                        }
                    }
                }
            }
            return ret;
        }

        private void docDetaliuDGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView dg = sender as DataGridView;
            DataSets.ESRPDataSet.DocumenteDetaliuRow sr = ((DataRowView)documenteDetaliuBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteDetaliuRow;
            DataSets.ESRPDataSet.DocumenteRow dr = ((DataRowView)documenteBindingSource.Current).Row as DataSets.ESRPDataSet.DocumenteRow;
            if (sr == null || dr==null)
                return;
            if (docDetaliuDGV[IDArticolColumn.Index, e.RowIndex].Value == DBNull.Value)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare", "Vă rugăm să selectaţi ARTICOLUL înainte de a genera liniile documentului!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, dr);
                mbt.AddButton("Iesire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                return;
            }

            if (e.ColumnIndex == CantComandataColumn.Index || e.ColumnIndex == StocIntratColumn.Index)
            {
                ShowWzdComenziStocuri(e.ColumnIndex,e.RowIndex,sr,dr);
            }
            
        }

        private void ReceptieCB_Validating(object sender, CancelEventArgs e)
        {
            if (LinkSourceBindingSource.Count != 0)
            {
                e.Cancel = true;
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare", "Documentul are atasat un document de iesire cu stoc diferit de 0!\n Eliminati legatura inainte de a debifa receptia!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, LinkSourceBindingSource.Current);
                mbt.AddButton("Iesire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
            }
        }

        private void ShowWzdComenziStocuri(Int32 ColumnIndex,Int32 RowIndex, DataSets.ESRPDataSet.DocumenteDetaliuRow sr, DataSets.ESRPDataSet.DocumenteRow dr)
        {
            Decimal cantR = Decimal.Zero;
            if (docDetaliuDGV[CantitateColumn.Index, RowIndex].Value != DBNull.Value)
            {
                cantR = Convert.ToDecimal(docDetaliuDGV[CantitateColumn.Index, RowIndex].Value);
            }
            String tipLink = "CM";
            if(ColumnIndex == StocIntratColumn.Index || ColumnIndex == CantitateColumn.Index)
                tipLink = "ST";

            ComenziWizFrm frm = new ComenziWizFrm(ModuleInfo, sr.IDArticol, sr.IDDocumentDetaliu, -1, dr.IDTipDocument, tipLink, cantR);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //parcurge randurile selectate din grid
                Decimal TotalCant = Decimal.Zero;

                LinkBindingSource.Filter = "Tip='" + tipLink + "'";
                ///sterge toate inregistrarile corespunzatoaare 
                foreach (DataRowView drs in LinkBindingSource) 
                    LinkBindingSource.Remove(drs);


                foreach (DataGridViewRow dgvr in frm.comenziDGV.Rows)
                { 
                    if (ColumnIndex == StocIntratColumn.Index || ColumnIndex == CantitateColumn.Index || ColumnIndex == CantComandataColumn.Index)
                    {
                        /// Se adauga randul nou selecta la comanda
                        /// 
                        TotalCant += Convert.ToDecimal(dgvr.Cells[frm.IndexCantitate].Value);

                        if (Convert.ToDecimal(dgvr.Cells[frm.IndexCantitate].Value) != Decimal.Zero)
                        {
                            DataRowView ret = LinkBindingSource.AddNew() as DataRowView;
                            DataSets.ESRPDataSet.DocumenteDetaliuLinkRow ddrl = ret.Row as DataSets.ESRPDataSet.DocumenteDetaliuLinkRow;
                            if (ddrl != null)
                            {
                                //ddrl.IDDocDetaliuDest = sr.IDDocumentDetaliu;
                                ddrl.IDDocDetaliuSursa = Convert.ToInt32(dgvr.Cells[frm.IndexIDDocDetaliuSursa].Value);
                                ddrl.Cantitate = Convert.ToDecimal(dgvr.Cells[frm.IndexCantitate].Value);
                                ddrl.Tip = tipLink;
                                ddrl.EndEdit();
                            }
                        }
                        LinkBindingSource.EndEdit();
                        ///seteaza cantitatea
                        ///
                    }
                }
                LinkBindingSource.EndEdit();
                if (ColumnIndex == StocIntratColumn.Index || ColumnIndex == CantitateColumn.Index)
                    if (docDetaliuDGV[CantitateColumn.Index, RowIndex].Value == DBNull.Value || Convert.ToDecimal(docDetaliuDGV[CantitateColumn.Index, RowIndex].Value) != TotalCant)
                        docDetaliuDGV[CantitateColumn.Index, RowIndex].Value = TotalCant;
               


            }
        }

        private void docDetaliuDGV_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            //GestiuneaStocurilorProc(e);
        }

        /// <summary>
        ///  completeaza data scadentei facturii
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataDocDTP_Validated(object sender, EventArgs e)
        {
            DataSets.ESRPDataSet.DocumenteRow rd = ((DataRowView)documenteBindingSource.Current).Row
                as DataSets.ESRPDataSet.DocumenteRow;
            if (rd.IDTipDocument == 0)
            {
                if (dataScadentaDTP.Value != dataDocDTP.Value.AddDays(FSRow.ZileScadentaFurnizor))
                    dataScadentaDTP.Value = dataDocDTP.Value.AddDays(FSRow.ZileScadentaFurnizor);
            }
            if (rd.IDTipDocument == 1)
            {
                if (dataScadentaDTP.Value != dataDocDTP.Value.AddDays(FSRow.ZileScadentaClient))
                    dataScadentaDTP.Value = dataDocDTP.Value.AddDays(FSRow.ZileScadentaClient);
            }
        }

        private void iDRegimFiscalCB_Validated(object sender, EventArgs e)
        {
            if (documenteBindingSource.Current == null || _initDialog)
                return;
            ComboBox contr = (ComboBox)sender;
            Int16 _regimFiscalInitial = Convert.ToInt16(contr.SelectedValue);
            Int32 tipDoc = 0;
            if (tipDocumentCB.SelectedValue != null)
                tipDoc = Convert.ToInt32(tipDocumentCB.SelectedValue);
            foreach (DataGridViewRow dr in docDetaliuDGV.Rows)
            {
                if (Convert.ToInt16(dr.Cells[regimFiscalColumn.Index].Value) != _regimFiscalInitial)
                {
                    dr.Cells[regimFiscalColumn.Index].Value = contr.SelectedValue;
                    Decimal Val = Decimal.Zero;
                    if (dr.Cells[ValoareTotalaColumn.Index].Value != DBNull.Value)
                        Val = Convert.ToDecimal(dr.Cells[ValoareTotalaColumn.Index].Value);
                    CalculeazaTVALinie(dr.Index, Val, Convert.ToInt16(contr.SelectedValue), tipDoc);
                }
            }
            eSRPDataSet.DocumenteDetaliu.IDRegimFiscalColumn.DefaultValue = _regimFiscalInitial;
        }

        private void dataDocDTP_ValueChanged(object sender, EventArgs e)
        {
            if (FSRow.DataReceptieEgalaDataFactura)
                dataDocReceptieDTP.Value = dataDocDTP.Value;
        }

    }


    public class InfoDimensiune
    {
        public String valoareInitiala = String.Empty;
        public Int16 idTipDimensiune = 0;
        public Boolean areDBRec = false;

        public InfoDimensiune(String vI, Int16 idT)
        {
            valoareInitiala = vI;
            idTipDimensiune = idT;
        }
    }


    public class DocumenteTableAdapterEx : DataSets.ESRPDataSetTableAdapters.DocumenteTableAdapter
    {
        public DocumenteTableAdapterEx()
            : base()
        {

        }
        public void SetTableName(String an)
        {
            foreach (SqlCommand cmd in this.CommandCollection)
            {
                if (cmd.CommandText.Contains("dbo.Documente"))
                    cmd.CommandText = cmd.CommandText.Replace("FROM dbo.Documente", "FROM [Documente" + an + "]");
                else
                    cmd.CommandText = cmd.CommandText.Replace("FROM Documente", "FROM [Documente" + an + "]");
            }
        }


    }

    public class DocumenteDetaliuTableAdapterEx : DataSets.ESRPDataSetTableAdapters.DocumenteDetaliuTableAdapter
    {
        public DocumenteDetaliuTableAdapterEx()
            : base()
        {

        }
        public void SetTableName(String an)
        {
            foreach (SqlCommand cmd in this.CommandCollection)
            {
                if (cmd.CommandText.Contains("dbo.DocumenteDetaliu"))
                    cmd.CommandText = cmd.CommandText.Replace("FROM dbo.DocumenteDetaliu", "FROM [DocumenteDetaliu" + an + "]");
                else
                    cmd.CommandText = cmd.CommandText.Replace("FROM DocumenteDetaliu", "FROM [DocumenteDetaliu" + an + "]");
            }
        }
    }
    
}
